0
のは、私は私のコントローラであるとしましょう:Railsでは、collection_selectヘルパーメソッドから選択した値を取得する方法は?
@parts = Part.all
とビューのフォームで:
<%= f.collection_select(:part_id, @parts, :id, :title, { :prompt => true } %>
それは新しい作成/アクションのために働いて、editアクションがあまりにも動作しますが、私はどのように知っていただきたいと思いますネストされたフォームなので、別のモデルで検索を行うための選択された値を取得します。
または、唯一の方法は、いくつかのJavaScriptを使用して取得しますか?
はこう:
<%= debug f.object.part %>
を私はこれを取得:
--- !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
私は今の場合のみ、属性が "価格" です。
は値やってアクセスしようとしたことがあり:<%= f.object.part.price %>
をしかし、それはエラーを返します:
undefined method `price' for nil:NilClass
トレースは私に私も持っているヘルパーメソッドに関連したものを示しています。
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'
このエラーが発生するヘルパーメソッド:
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.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, "add_fields(this, '#{association}', '#{escape_javascript(fields)}')")
end
このヘルパーメソッドへのリンクを削除するとf.object.part.price作品を呼び出します。
あなたはどう思いますか?コントローラにはこのようなものを設定する