例如:
class Post < ActiveRecord::Base
belongs_to :article
end
class Article < ActiveRecord::Base
has_many :posts
end
我需要在文章中更改状态,当我删除最后一个帖子或将最后一个帖子中的文章更改为 nil 时,我有两个具有共同逻辑的操作:
def destroy
post = Post.find(params[:id])
article = post.article
post.destroy
if article && !article.posts.present?
if article.status == 2
article.status = 1
article.save
notice = " and it was last post for article #{article.title} and article status change to empty!"
end
end
redirect_to(posts_path(:by_status=>:all), :notice => "Post was successfully deleted #{notice}")
end
def remove_from_article
post = Post.find(params[:id])
article = post.article
post.article = nil
post.save
if article && !article.posts.present?
if article.status == 2
article.status = 1
article.save
notice = " and it was last post for article #{article.title} and article status change to empty!"
end
end
redirect_to(posts_path(:by_status=>:all), :notice => "Post was successfully updated #{notice}")
end
如何重构此代码,我应该在过滤器之后还是在过滤器周围使用,如果是,我如何将文章传递给它?