在我的导轨项目中,我有两个型号,Car Make&汽车模型,具有1:M的关系(即一辆奥迪拥有许多奥迪车型)。
在我的“视图”页面中,我想要一个包含两个输入字段的表单,用于car make&汽车模型。理想情况下,我将能够输入汽车制造(即奥迪),第二个输入区域将有一个下拉菜单,其中包含所有可用于制造的车型(2016款奥迪A6,2017款奥迪A7)。
我已经设置了所有关系,并且在模型中我保存了make的外键。
目前在_form.html.erb我有
<div class="field">
<%= f.label :make_id, "Make:"%><br>
<%#= f.number_field :make_id %>
<%= f.collection_select :make_id, Make.all,
:id,:makes_info, {:include_blank => 'Please Select'} %>
</div>
<div class="field">
<%= f.label :model_id, "Model:" %><br>
<%= f.collection_select :model_id, Model.all,
:id,:model_info, {:include_blank => 'Please Select'} %>
</div>
答案 0 :(得分:0)
答案 1 :(得分:0)
它被称为dynamic select boxes
:
#config/routes.rb
resources :makes do
get :models, on: :collection #-> url.com/makes/models
end
#app/controllers/makes_controller.rb
class MakesController < ApplicationController
def models
@make = Make.find(params[:make][:make_id])
respond_to do |format|
format.js
end
end
end
#app/views/makes/models.js.erb
$select = $("select#models");
$select.empty();
<% @make.models.each do |model| %>
$select.append($('<option>').text(<%=j model.name %>).attr('value', <%= model.id %>));
<% end %>
#views
<%= f.collection_select :make_id, Make.all, :id, :makes_info, {include_blank: 'Please Select'}, { data: { remote: true, url: make_models_path }} %>
<%= f.collection_select :model_id, Model.all, :id,:model_info, {include_blank: 'Please Select'}, { id: "models" } %>