0

例えば:

class Post < ActiveRecord::Base
  belongs_to :article
end 

class Article < ActiveRecord::Base
  has_many :posts
end

記事のステータスを変更する必要があります。最後の投稿を削除するか、最後の投稿で記事をnilに変更すると、共通論理を持つ2つのアクションがあります。

  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 に答える