weixin_33747129 2014-04-22 20:12 采纳率: 0%
浏览 25

使用参数渲染新动作

I have ajax-based select in my form, my form:

= 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

and partial:

- 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

I test, and could have such case: when I didn't enter something and submit form - I see validation errors and my select values are nil, but how and in which action to append this something like this:

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

I use rails4.

What I do wrong and how to solve my problem?

  • 写回答

1条回答 默认 最新

  • 叼花硬汉 2014-04-26 17:10
    关注

    Try passing your form variable through to the partial; as the select_tag on its own won't be able to associate it's value with the form_for @car.

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

    Then, in the partial:

    = form.select "by_model ..."

    To be more specific, that form_for @car clause at the top of your form says 'wrap eveything in this block in a 'car' object when it is submitted'. So right now the form you're submitting has values like this:

    car[vehicle_manufacturer_id]
    car[vehicle_model_id]
    by_model
    

    But you need to wrap that last by_model attribute in the car array like the others:

    car[vehicle_manufacturer_id]
    car[vehicle_model_id]
    car[by_model]
    
    评论

报告相同问题?