For example:
class Post < ActiveRecord::Base
belongs_to :article
end
class Article < ActiveRecord::Base
has_many :posts
end
I need change status in article, when I delete last post or change article to nil in last post, I have two actions with common logic:
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
How can I refactoring this code, should I use after or around filter, if yes how can I pass article to it?
You can use the before_destroy callback, so something like:
You can use
selfto get your model and traverse any relationships you want. In this case it’s getting the article.