我想讓用戶在同一表單的兩個不同下拉菜單中輸入兩個不同的東西,它會將整數存儲到檢查表中。Rails模式中的多個輸入字段以一個整數屬性
我希望用戶能夠在一個下拉列表中選擇model_name
,在另一個下拉列表中選擇manufacturer
。結果將在表格中存儲一個bat_id
整數。 (告訴你用戶選擇哪隻蝙蝠)
我已經看到有幾個關於日期&時間的問題,但它們直接將值存儲在模型中。我正在嘗試存儲一個整數 - bat_id
,以便bat_id將直接將審閱模型鏈接到蝙蝠模型。
例子我發現接近:
- How do ruby on rails multi parameter attributes really work (datetime_select)
- Rails multiple fields to one model attribute
- Using multiple input fields for one attribute
- Rails Update Single Attribute with Multiple Fields
我現在的形式:
<%= form_for(@review) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field" align= "center">
<h3>Select Brand</h3>
<%= f.collection_select :manufacturer_id, Manufacturer.all, :id, :manufacturer, include_blank: true %>
<h3>Select Bat</h3>
<%= f.grouped_collection_select :bat_id, Manufacturer.all, :bats, :manufacturer, :id, :model_year_and_name, include_blank: true %>
<h3>What do you like about this bat?</h3>
<%= f.text_area :pros, placeholder: "Enter what you like..." %>
<h3>What do you not like about this bat?</h3>
<%= f.text_area :cons, placeholder: "Enter what you don't like..." %></br>
</div>
<div align="center">
<%= f.submit "Add Review", class: "btn btn-large btn-info" %>
</div>
<% end %>
我正在提交到review
表並試圖將這兩個都提交到bat_id
屬性。
<h3>Select Brand</h3>
<%= f.collection_select :manufacturer_id, Manufacturer.all, :id, :manufacturer, include_blank: true %>
<h3>Select Bat</h3>
<%= f.grouped_collection_select :bat_id, Manufacturer.all, :bats, :manufacturer, :id, :model_year_and_name, include_blank: true %>
在我的蝙蝠模型我有:has_many :reviews
&在我的評論模式我有:belongs_to :bat
UPDATE:是否可以使用隱藏字段的javascript和我的兩個輸入組合確定我的一個輸出bat_id?
更新我改變了我的下拉列表中的代碼是什麼在起作用,讓我在manufacturer_id
& bat_id
同時輸入時進行選擇。但我仍然認爲有一種方法可以在我的review
模型中存儲一個值。我使用JavaScript非常相似,this
是的我打算使用JavaScript來顯示只有製造商被選中的製造商的蝙蝠。 - 這將消除破損的用戶界面問題是否正確?對於解決方案#1,您提供了冗餘,並通過存儲「manufacturer_id」兩次違反DRY原則。 (我已經將'manufacturer_id'存儲在蝙蝠模型中)我可以再做一次,但我的目標是使用DRY。對於解決方案#2它確實有效,但我會成爲100-200個蝙蝠,我不想在UI側以30個蝙蝠的形式重複製造商的名稱。 – Daniel
我不確定這部分是什麼意思 - 你能解釋得更好嗎? 'Bat.all.sort {| a,b | a.manufacturer_model_year_and_name <=> b.manufacturer_model_year_and_name}'我的猜測是來自蝙蝠模型的所有字段都使用a.manufacturer ....和b.manufacturer ...在數組中排序,這些屬性是模型中定義的屬性。 '| a,b |'&'<=>'是什麼意思? – Daniel
是的,如果您使用JavaScript來僅顯示選定製造商的蝙蝠,那麼解決了用戶界面問題。 –