例えば:
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
このコードをリファクタリングするにはどうすればよいですか?フィルターの後または周囲で使用する必要がありますか?はいの場合、どのように記事をコードに渡すことができますか?