In Rails, how to get the selected value from the collection_select helper method?
Let's say I have on my controller:
@parts = Part.all
and on the view form:
<%= f.collection_select(:part_id, @parts, :id, :title, { :prompt => true } %>
It's working for the new/create actions, edit action works too but I would like to know how to get the selected value for doing a find on another model, since it's a nested form.
Or the only way is get it using some javascript?
Doing:
<%= debug f.object.part %>
I get this:
--- !ruby/object:Part
attributes:
id: 1
title: Pearl 02
part_type_id: 36
created_at: 2011-07-28 07:52:09.000000000Z
updated_at: 2011-07-28 08:34:02.000000000Z
set: !!null
price: 3.53
changed_attributes: {}
previously_changed: {}
attributes_cache: {}
marked_for_destruction: false
destroyed: false
readonly: false
new_record: false
Which the only attribute I want for now is "price".
Have tried to access the value doing:
<%= f.object.part.price %>
but then it returns an error:
undefined method `price' for nil:NilClass
the trace shows me something related to an helper method I have also.
app/views/items/_item_part_fields.html.erb:7:in `_app_views_items__item_part_fields_html_erb___1683960156823546996_2175548540_683257483947746572'
app/helpers/application_helper.rb:46:in `block in link_to_add_fields'
app/helpers/application_helper.rb:45:in `link_to_add_fields'
the helper method that causes this error:
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.开发者_JAVA技巧to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "add_fields(this, '#{association}', '#{escape_javascript(fields)}')" )
end
Removing the link to this helper method and calling f.object.part.price works.
What you think?
<% f.object.part_id = XXX %>
<%= f.collection_select(:part_id, @parts, :id, :title, { :prompt => true } %>
Or better to set this stuff in controller (since it is nested form I can't write solution with controller)
精彩评论