0

例如:

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

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

4

1 回答 1

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来获取您的模型并遍历您想要的任何关系。在这种情况下,它正在获取文章。

于 2012-10-18T16:35:35.963 回答