强文我试图通过"data-remote attribute for select boxes"制作动态选择框。在控制台中,似乎我得到了正确的参数(所选make的id),但我无法弄清楚如何将它传递给控制器以获得匹配make_id:s的模型。
来自_form.html.erb的attachment_vehicles构成部分
<div class="vehicle_field">
<%= f.fields_for :attached_vehicles do |av| %>
<p>Select make</p>
<%= av.select :make, (@makes.collect { |m| [m.make_name, m.id] }), { include_blank: "Select make" }, { data: { remote: true, url: "update_make_models", name: "make", update: "#diy_attached_vehicles_attributes_0_model"} } %><br>
<p>Select model</p>
<%= av.collection_select :model, @models, (render "make_models/make_model"), { prompt: "Select model" } %><br>
...
<% end %>
</div>
../视图/小五金/ update_make_models.coffee
$.empty()
.append("<%= escape_javascript(render "make_models/make_model") %>")
../ diys_controller.rb
...
def update_make_models
@models = MakeModel.where("make_id = ?", params[:make])
end
def new
@diy = Diy.new
@step = @diy.steps.new
@attached_vehicle = @diy.attached_vehicles.new
@step.add_images_to_steps.new
@makes = Make.all
@models = MakeModel.where("make_id = ?", params[:make_id])
end
...
../视图/ make_models / _make_model.html.erb
<% @models.collect do |models| %>
<option value="<%= models.id %>"><%= models.make_model_name %></option>
<% end %>
以下是选择make in make select box后我在控制台中获得的内容
Started GET "/diys/update_make_models?diy%5Battached_vehicles_attributes%5D%5B0%5D%5Bmake%5D=12" for ::1 at 2016-02-18 20:22:35 +0200 Processing by DiysController#update_make_models as JS
Parameters: {"diy"=>{"attached_vehicles_attributes"=>{"0"=>{"make"=>"12"}}}}
MakeModel Load (1.0ms) SELECT "make_models".* FROM "make_models" WHERE (make_id = NULL)
Rendered make_models/_make_model.html.erb (3.0ms)
Rendered diys/update_make_models.coffee (491.0ms)
Completed 200 OK in 628ms (Views: 626.5ms | ActiveRecord: 1.0ms | Solr: 0.0ms)
-------------------------------------------- -------------------------------------------------- -------------------------------------- 的修改
NameError (undefined local variable or method `attached_vehicles_attributes' for #<DiysController:0x5757648>):
app/controllers/diys_controller.rb:28:in `update_make_models'
答案 0 :(得分:1)
您的ListBox.Selected
哈希是(根据日志):params
。所以,如果你想从中获取{"diy"=>{"attached_vehicles_attributes"=>{"0"=>{"make"=>"12"}}}}
,你应该写:
:make_id