I’ve got a User model that has many Items. A Rating belongs to a User and an Item.
In the DB, I have set ratings.user_id to be not NULL.
when I am creating an Item, I would like to do this:
def create current_user.items.create(params[:item]).ratings.create(params[:rating] redirect_to items_path end
However, this balks with an SQL error ‘user_id cannot be nil’
so I rewrote the create method as
def create current_user.items.create(params[:item]).ratings.create(params[:rating].merge({:user_id => current_user})) redirect_to items_path end
which works fine.
However, I had thought that chaining the create methods off the current user’s receiver would have populated the rating’s user_id. Anyone know why not?
TIA.
I’d recommend you normalize this if possible in the database. Maybe take out the user_id attribute from the ratings table and if you need it in your model get it through a join using a :through method