I got an Object, Rating, with 2 fields, user_id and 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
On create i want to set user_id and value to the given values from the Controller:
@rating = Rating.create(user_id: 1, value: 2)
But after i created it, it should not be possible to change the user_id attribute. Just the value attribute. So after that:
@rating.update(user_id: 2, value: 3)
@rating.user_id should still return 1, but value should be 3.
My idea was to use before_update to revert the changes, but that does not look right to me.
Is the another way to do it?
i hope i could make it more clear whats my problem..
Thanks
The Controller looks like this:
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
You could do that with some strong_params. Simply don't allow user_id
when updating. Something along these lines:
class RatingsController
def create
@rating = Rating.create(create_rating_params)
...
end
def update
@rating = Rating.find(params[:id])
@rating.update_attributes(update_rating_params)
...
end
private
def create_rating_params
params.require(:rating).permit(:user_id, :value)
end
def update_rating_params
params.require(:rating).permit(:value)
end
end