[英]Rails 3, update linked model in controller on record creation
In my rails app I have the Posts Model, which has_many Comments. 在我的rails应用程序中,我具有Posts模型,该模型具有has_many评论。
Everytime a new comment is posted, I'd like the updated_at column in the Posts model to be updated. 每次发布新评论时,我都希望更新Posts模型中的updated_at列。
I assume I need to do this in the create method of the Comments controller. 我假设我需要在Comments控制器的create方法中执行此操作。
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! 谢谢!
-Elliot -艾略特
You can use the :touch awesomess to update the updated_at 您可以使用:touch awesomess更新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. 然后,当您保存评论时,它将触摸该帖子并更新updated_at。
More infos: 更多信息:
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. 另外,您也不想从Comment调用self.post.update_attributes,因为那样会占用过多的Post特定细节。
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.