我有一个对象Rating,有两个字段user_id和value。
class CreateRatings < ActiveRecord::Migration[5.1]
def change
create_table :ratings do |t|
t.belongs_to :user
t.integer :user_id
t.decimal :value
end
end
end
在创建时,我想将 user_id 和 value 设置为来自控制器的给定值:
@rating = Rating.create(user_id: 1, value: 2)
但是在我创建它之后,应该无法更改user_id 属性。只是value 属性。所以在那之后:
@rating.update(user_id: 2, value: 3)
@rating.user_id 仍应返回 1,但值应为 3。
我的想法是使用before_update来恢复更改,但这对我来说并不正确。
是另一种方法吗?
我希望我能更清楚我的问题是什么..
谢谢
更新
控制器看起来像这样:
def create
Rating.create(rating_params)
end
def edit
Rating.find(params[:id]).update(rating_params)
end
private
def rating_params
params.require(:rating).permit(:user_id, :value)
end