我正在使用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
在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
答案 0 :(得分:2)
当回调不成功时,您可以向对象添加错误:
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
然后,当@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
答案 1 :(得分:2)
在控制器中使用rescue_from
来捕获错误:
class TweetsController
rescue_from Twitter::Error, with: :error
def error
redirect_to root_path, alert: "Please fix the error #{error.message}"
end
end
此外,如果您想在模型和控制器中捕获错误,您可以通过重新提升来实现:
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
self.twottered = false
raise error
end
end
end