开发者

Rails 3, update linked model in controller on record creation

In my rails app I have the Posts Model, which has_many Comments.

Everytime a new comment is posted, I'd like the updated_at column in the Posts model to be updated.

I assume I need to do this in the create method of the Comments controller.

Does anyone have some idea of the specific way to do this?

   @post = Post.find_by_id(@comment.post_id)
   @post.save!

Did not work.

Thanks!

开发者_如何学C

-Elliot


You can use the :touch awesomess to update the updated_at

So if you have

class Post
  has_many :comments
end

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

Then when you save a comment, it will touch the post and update the updated_at.

More infos:

  • SO Question
  • Rails Doc
  • Blog Post


I'd implement it in your commment model

class Comment < ActiveRecord::Base
  belongs_to :post

  def after_create
    post.update_attribute(:updated_at, Time.now)
  end
end


You want to keep as much as possible out of the controller. The controller is only for directing user input and output to the right places.

Also, you wouldn't want to be calling self.post.update_attributes from the Comment because that would be tying in too many Post-specific details.

# in comment.rb
after_save :update_post_activity

def update_post_activity
  self.post.update_activity if self.post?
end

# in post.rb
def update_activity
  self.update_attributes(:updated_at => Time.now)
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜