我一直在玩,但我似乎无法弄清楚如何更新父模型的属性。
我有一个名为Enhancement的模型和一个名为EnhancementComment的模型。因此,增强功能可以发表评论。
我成功地工作了:
增强评论控制器:
def create
@enhancement = Enhancement.friendly.find(params[:enhancement_id])
@enhancement_comment = @enhancement.enhancement_comments.create!(enhancement_comment_params)
respond_to do |format|
if @enhancement_comment.save
format.html { redirect_to @enhancement }
format.json { render action: 'show', status: :created, location: @enhancement_comment }
else
format.html { render action: 'new' }
format.json { render json: @enhancement_comment.errors, status: :unprocessable_entity }
end
end
end
我想做什么:创建评论时,我想更新增强模型中的名为:updated_at的属性(而不是EnhancementComment模型)。
我该怎么做?
感谢。
更新
以下是我现在所拥有的:
class Enhancement < ActiveRecord::Base
# Associations
has_many :enhancement_comments, class_name: 'EnhancementComment', dependent: :destroy
class EnhancementComment < ActiveRecord::Base
# Associations
belongs_to :enhancement, touch: true
当我创建新评论时,这似乎并不起作用。
答案 0 :(得分:0)
在子关联上将touch
选项设置为true
。对于您要执行的操作,显式,在保存时更新关联另一端的updated_at
。
class Enhancement < ActiveRecord::Base
has_many :comments, class_name: 'EnhancementComment'
end
class EnhancementComment < ActiveRecord::Base
belongs_to :enhancement, touch :true
end
:touch
如果为true,则在保存或销毁此记录时将触摸关联对象(设置为now的updated_at / on属性)。如果指定符号,除了updated_at / on属性外,该属性将使用当前时间进行更新。