重构控制器操作

时间:2012-10-18 16:01:27

标签: ruby-on-rails controller refactoring

例如:

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

我如何重构此代码,我应该在过滤器之后使用,如果是,我该如何将文章传递给它?

1 个答案:

答案 0 :(得分:0)

您可以使用before_destroy回调,例如:

class Post < AR::Base
  belongs_to :article

  before_destroy :change_article_status

  private
  def change_article_status
    article = self.article
    # Status update logic here
  end
end

您可以使用self获取模型并遍历您想要的任何关系。在这种情况下,它正在收到文章。