Reputation: 61
I have this lines in my form
<%= f.fields_for :attached_vehicles do |av| %>
<p>Select make</p>
<%= av.select :make, options_for_select(@makes.collect { |make|[make.make_name, make.id] }), { include_blank: "Select make" }, {} %>
...
<% end %>
which renders this in html
<select name="diy[attached_vehicles_attributes][0][make]" id="diy_attached_vehicles_attributes_0_make">
<option value="">Select make</option>
<option value="1">ACURA</option>
<option value="2">ALFA ROMEO</option>
<option value="3">AM GENERAL</option>
<option value="4">AMERICAN IRONHORSE</option>
<option value="5">AMERICAN LAFRANCE</option>
...
</select>
So now it saves the value of selected option to database, and i need it to save content of selected option.
Also I can't just replace make.id
with make.make_name
in "options_for_select", because I need value to be id so my other dynamic select box gets right options depending on selected option.
------------------------------------------------------------------------------------------------------------------------------------EDIT
So I did as Dharam suggested
...
def diy_params
params[:diy][:attached_vehicles_attributes].each_with_index do |make_id, index|
params[:diy][:attached_vehicles_attributes][index][:make] = Make.find(make_id).make_name
end
params.require(:diy).permit(:title, :summary, :tip, :warning, attached_vehicles_attributes: [:make, :model, :start_year, :end_year], steps_attributes: [:step_content, add_images_to_steps_attributes: [:image]])
end
...
And I keep getting this error
Couldn't find all Makes with 'id': (0, {"make"=>"12", "model"=>"XPEDITOR", "start_year"=>"2002", "end_year"=>"2010"}) (found 0 results, but was looking for 2)
So i have tried
...Make.find(make_id.first.make).make_name
and multiple other things but didn't get it working, what i'm doing wrong?
------------------------------------------------------------------------------------------------------------------------------------EDIT2
The value of make_id seems to be
(0, {"make"=>"12", "model"=>"XPEDITOR", "start_year"=>"2002", "end_year"=>"2010"})
because it tries to find Make with it as id.
And parameters in console looks like
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Kr4yvJUPCzUagUaW1glt69HEychEz+6QyHpGjKVKQ883rTUl0pZD+9SZSaQujHgM9k7jRt0vP1WTV5fMp8xyJw==", "diy"=>{"attached_vehicles_attributes"=>{"0"=>{"make"=>"12", "model"=>"XPEDITOR", "start_year"=>"2002", "end_year"=>"2010"}}, "title"=>"afaf", "summary"=>"AFSfAS", "tip"=>"FAF", "warning"=>"fdsgfsd", "steps_attributes"=>{"0"=>{"step_content"=>"gsdgsdg"}}}, "commit"=>"Create Diy"}
Upvotes: 0
Views: 114
Reputation: 6438
Before processing the params
in your controller, you can do the following:
params[:diy][:attached_vehicles_attributes].each do |index, make_attributes|
params[:diy][:attached_vehicles_attributes][index]['make'] = Make.find(make_attributes['make']).name
end
You can replace Make
model with the actual model that is backing the @models
.
Upvotes: 1