用params渲染新动作

时间:2014-04-22 20:12:57

标签: ruby-on-rails ajax

我的表单中有基于ajax的选择,我的表单:

= form_for @car, :html => {:id => "new-car-form"} do |f|
  - if @car.errors.any?
    - if @car.errors.any?
      .flash-notice
        %b= "Ошибки в полях: #{@car.errors.count} ошибка(и)"
        %ul
          - @car.errors.each do |attr,msg|
            %li= msg
  .field
    = f.label :vehicle_manufacturer_id, "Марка"
    = f.select :vehicle_manufacturer_id, options_from_collection_for_select(VehicleManufacturer.all, :id, :name, @car.vehicle_manufacturer_id), {:prompt => "Выберите марку"}, required: true, id: "manufacturer-select"
  .field
    = f.label :vehicle_model_id, "Модель"
    #models-area
      = render :partial => 'models', :object => @models

和部分:

- if @models.present? 
  = select_tag "by_model", options_from_collection_for_select(@models, "id", "name", selected: @selected), :prompt => "Выберите модель", required: true, id: "model-select"
- else
  = select_tag "by_model", nil, :prompt => "Выберите модель", required: true, id: "model-select", disabled: true

我测试了,可能有这样的情况:当我没有输入内容并提交表单时 - 我看到验证错误,我的选择值是零,但是如何以及在哪个操作中添加这样的内容:< / p>

@models = VehicleModel.where(manufacturer_id: @car.vehicle_manufacturer_id)
    @selected = @car.vehicle_model_id

我使用rails4。

我做错了什么以及如何解决我的问题?

1 个答案:

答案 0 :(得分:0)

尝试将表单变量传递给partial;因为select_tag本身无法将其值与form_for @car相关联。

= render :partial => 'models', :object => @models, :form => f

然后,在部分:

= form.select "by_model ..."

更具体地说,表单顶部的form_for @car子句表示'在提交'时在'car'对象中将此块中的eveything包装起来'。所以现在你提交的表格有这样的价值:

car[vehicle_manufacturer_id]
car[vehicle_model_id]
by_model

但是你需要像其他人一样包装汽车数组中的最后by_model属性:

car[vehicle_manufacturer_id]
car[vehicle_model_id]
car[by_model]