2016-02-29 37 views
0

我在我的形式保存選擇框的選項內容,而不是價值

<%= 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 %> 

此線,使得這個在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> 

所以現在將保存選項數據庫的價值,我需要它來保存選定選項的內容。 另外,我不能只用替換make.make_name在「options_for_select」,因爲我需要值爲id,所以我的其他動態選擇框根據選定的選項得到正確的選項。

--------------------------------------------- -------------------------------------------------- -------------------------------------編輯

所以,我沒有爲Dharam建議

... 
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 
... 

,我不斷收到此錯誤

找不到所有 '身份證' 使:(0,{ 「使」=> 「12」, 「模式」=> 「XPEDITOR」 ,「start_year」=>「2002」,「end_year」=> 「2010」})(搜索到0,但一直在尋找2)

這就是我一直

... Make.find(make_id.first.make).make_name

和多個其他的東西,但沒有得到它的工作,我做錯了什麼?

--------------------------------------------- -------------------------------------------------- ------------------------------------- EDIT2

make_id的值似乎是

(0,{ 「使」=> 「12」, 「模式」=> 「XPEDITOR」, 「START_YEAR」=> 「2002」, 「END_YEAR」=> 「2010」})

因爲它試圖找到與它作爲身份證。

和參數在控制檯看起來像

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"} 
+1

將內容分配到提交的隱藏字段?或者在提交後按價值查看內容。 –

回答

1

處理在控制器的params之前,您可以執行以下操作:

params[:diy][:attached_vehicles_attributes].each do |index, make_attributes| 
    params[:diy][:attached_vehicles_attributes][index]['make'] = Make.find(make_attributes['make']).name 
end 

您可以替換Make模型與被支持的實際模型@models

+0

編輯我的問題,如果你可以檢查我在做什麼錯誤,會很好:) –

+0

嘗試在上面的'each_with_index'循環中打印'make_id'的值。還提供控制器實際接收的'params'。你可以從rails開發中獲得'params'。登錄或從控制檯。 – Dharam

+0

編輯我的問題。 –

相關問題