添加嵌套对象时如何跳过updated_at字段?

时间:2014-11-01 09:44:30

标签: ruby-on-rails callback

我有以下几行:

puts @post.updated_at # -> 2014-11-01 09:34:13

@comment = @post.comments.build(comment_params.merge(user: current_user))
@comment.save

puts @post.updated_at # -> 2014-11-01 09:43:01

这显然会在给定帖子中添加评论,但也会更新@post对象中的updated_at列。有没有优雅的方法可以跳过它?

由于

更新:

现在我能想到的就是:

updated_at = @post.updated_at
@comment = @post.comments.build(comment_params.merge(user: current_user))
@comment.save
@post.update_column('updated_at', updated_at)

我认为这不是很好。

1 个答案:

答案 0 :(得分:1)

确保Comment模型中没有回调,导致此更新。

如果你没有通过@post对象进行构建,那么它就不会被触及。

@comment = Comment.create(comment_params.merge(user: current_user, post: @post))