Yuval Karmi
Yuval Karmi

Reputation: 26713

Where to put a piece of code in Ruby on Rails?

I have a post controller that has many comments. The post model has a field called has_comments which is a boolean (so I can quickly select from the database only posts that have comments). To create a new comment for a post, I use the create action of my comments controller.

After I create the comment I need to update my post's has_comments field and set it to true.

I can update this field from the create action of my comments controller, but that doesn't seem right - I feel that I should really be using the post's update action, but I'm not sure if it's right to call it (via send?) from the create action of the comments controller.

Where should the code for updating the post be? Thank you!

Upvotes: 1

Views: 211

Answers (3)

Dave Sims
Dave Sims

Reputation: 5128

Why clutter your database with another column when the interface is programmatic? Make has_comments a method on Post:

def has_comments
  comments.size > 0
end

Then implement a counter_cache as suggested to reduce the query load.

EDIT: Alternatively, after implementing a counter cache, you could use a named_scope on Post to retrieve all posts that have comments, using a single query, if that's the main goal:

class Comment
  belongs_to :post, :counter_cache => true
end

class Post
  named_scope :with_comments, {:conditions=>"comments_count > 0"}
end 

EDIT: You can also avoid the famous n+1 query problem by a judicious use of :include:

posts = Post.find(:all, :include => :comments)

Upvotes: 2

Salil
Salil

Reputation: 47472

use after_save in comment model

def after_save
  #this will set "has_comment" of the Specified Post to true if it's not true already
  self.post.update_attribute('has_comment', true) unless self.post.has_comment
end

Upvotes: 1

Slobodan Kovacevic
Slobodan Kovacevic

Reputation: 6888

You could use before_save callback in your model.

Even better way would be to use built in :counter_cache option which automatically caches the number of comments for each post. (see http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001835 under options for belongs_to)

Upvotes: 1

Related Questions