导轨| 拯救模型中的异常并使用控制器中的错误

The*_*Guy 1 twitter ruby-on-rails rescue

我正在使用twitter gem 来允许用户从我的应用程序发布推文。

这是我的 tweet.rb 文件

 class Tweet < ActiveRecord::Base
     belongs_to :user

     validates :user_id, :tweet, presence: true
     before_create :post_to_twitter

     def post_to_twitter
       begin
        user.twitter.update(tweet)
       rescue Twitter::Error => error
        // I want to do a redirect_to root_path, notice: "Please fix the error #{error.message}"
       // but its against MVC structure to pattern for a model to redirect, since its the task of a controller. How can I achieve this in controller
       end
     end
    end
Run Code Online (Sandbox Code Playgroud)

在 post_to_twitter 方法的救援块中,我想做一个redirect_to root_path, notice: "Please fix the error #{error.message}" ,但它反对 MVC 结构来模式化模型以重定向,因为它是控制器的任务。我怎样才能在控制器中实现这一点?

这是tweets_controller.rb 文件

class TweetsController < ApplicationController

      def new
        @tweet = Tweet.new
      end

      def create
        @tweet = Tweet.new(tweet_params)
        @tweet.user_id = current_user.id
        if @tweet.save
          redirect_to new_tweet_path, notice: "Your tweet has been successfully posted"
        else
          render 'new'
        end
      end

      private
      def tweet_params
        params.require(:tweet).permit(:tweet, :user_id)
      end

    end
Run Code Online (Sandbox Code Playgroud)

And*_*eko 5

当回调不成功时,您可以向对象添加错误:

def post_to_twitter
  begin
    user.twitter.update(tweet)
  rescue Twitter::Error => error
    # error will be appear in `@tweet.errors`
    errors.add(:base, "Please fix the error #{error.message}")
    false
  end
end
Run Code Online (Sandbox Code Playgroud)

@tweet.save然后,在返回时在控制器中执行您需要的操作false(由于回调不成功,它将返回 false):

def create
  @tweet = Tweet.new(tweet_params)
  @tweet.user_id = current_user.id
  if @tweet.save
    redirect_to new_tweet_path, notice: "Your tweet has been successfully posted"
  else
    # render 'new'
    redirect_to root_path, notice: @tweet.errors.full_messages.join(',')
  end
end
Run Code Online (Sandbox Code Playgroud)