I'm trying to add the user_id to a nested attribute that gets built by a parent controller but it doesn't seem to have the desired effect?
Ie. I have a model called Place.rb which accepts_nested_attributes_for :reviews
and has_many :reviews, :as => :reviewable, :dependent => :destroy
The nested attribute works fine and I build it inside the Places controller like so...
new action
@review = @place.reviews.build(:user_id => current_user.id)
create action
params[:place].merge(:user_id => current_user.id)
params[:place][:reviews_attributes].merge!(:user_id => current_user.id)* bad
@place = Place.new(params[:place])
this is the original, for the place model to get a user_id, now i need the user_id for the nested reviews model as well. It might seem odd that places and reviews both have user_ids, but people can add new reviews for the same place...
possibly like this but doesn't work:
@place = Place.new(params[:place].merge(:user_id => current_user.id, :reviews_attributes => { :user_id => current_user.id } ))
get the error: undefined method
with_indifferent_access' for 3:Fixnum`
or
@place = Place.new(params[:place].merge(:user_id => current_user.id, :reviews_attributes => { "0" => { :user_id => current_user.id }}))
which adds the correct user_id but replaces the content of the review with NULL ;-(
I was previously adding the user thru the form, but would like to do it thru the controller so that it only adds the user_id on creation, as a particular review might get updated by someone else and i don't want the update changing the user_id from the original writer...
old way which works:
<%= e.label :content, "Review" %><br />
<%= e.text_area :content, :rows => 20, :class => 'jquery_ckeditor' %><br />
<%= e.hidden_field :user_id, :value => current_user.id %> #want to remove this line
but thru the controller the build method with options has no effect? Any ideas? Can I not do this thru the build?
The output in log:
Parameters: {"commit"=>"Submit", "action"=>"create", "city_id"=>"prague",
"controller"=>"places", "place"=>{"address"=>"fsdfsdf", "name"=>"sdfsdfsd",
"reviews_attributes"=>{"0"=>{"content"=>"<p>\r\n\tsdfsdfsdfsdfsdfsdfsdf sdfsdfsdf</p>\r
\n"}}, "website"=>"", "city_id"=>"1036", "place_type"=>"1"}}