1

我一直在尝试在 rails 4.0 中使用 AJAX 实现动态依赖表单。我有一个bike模型,它has_one makemodel. 它也has_many quotesmodel目标是在选择第一个字段后填充第二个表单的集合字段 ( ) make

表单正确加载,一旦选择了第一个字段,就会进行 AJAX 调用,并返回适当的数据集(通过控制台中的 puts 确认)。但是,我无法弄清楚如何适当地渲染部分。我收到以下错误。我知道一旦通过 AJAX 调用呈现部分,就没有 f 变量,但是我该如何设计没有 f 变量的表单呢?

ActionView::Template::Error (undefined local variable or method `f' for #<#<Class:0x007f95b0fc2068>:0x007f95b54e2490>):
    1: <%= f.label :name, 'Model' %>
    2: <% if !current_models.blank? %>
    3:  <%= f.collection_select :name, current_models.collect{ |m| [m.name,m.id]}, :id , :name, include_blank: true %>
    4: <% else %>
  app/views/shared/_model_questions_fields.html.erb:1:in `_app_views_shared__model_questions_fields_html_erb__894239665582553972_70140482609500'
  app/controllers/quotes_controller.rb:70:in `update_model_select'

引号/new.html.erb

<%= form_for @quote do |f| %>
    <%= f.fields_for :bikes do |builder| %>
            <p><%= render 'shared/bike_questions_fields', :f => builder %></p>
    <% end %>
    <%= f.submit "Show Quote", class: "btn btn-large btn-primary" %>
<% end %>

'共享/bike_questions_fields'

<%= f.fields_for :makes do |builder| %>
    <p><%= render 'shared/make_questions_fields', :f => builder %></p>
<% end %>

<%= f.fields_for :models do |builder| %>
    <div id="bikeModels"
        <p><%= render 'shared/model_questions_fields', :f => builder, :current_models => [] %></p>
    </div>
<% end %>

'共享/model_questions_fields'

<%= f.label :name, 'Model' %>
<% if !current_models.blank? %>
    <%= f.collection_select :name, current_models.collect{ |m| [m.name,m.id]}, :id , :name, include_blank: true %>
<% else %>
    <%= f.collection_select :name, [], :id , :name, include_blank: true %>
<% end %>

报价控制器:

def update_model_select
    models = Model.where(:make_id=>params[:id]).order(:name) unless params[:id].blank?
    render :partial => "shared/model_questions_fields", :locals => { :current_models => models }
end

在quotes.js.coffee:

ready = ->
  jQuery ($) ->

  # when the #make field changes
  $("#quote_bikes_makes_name").change ->

    # make a POST call and replace the content
    make = $("select#quote_bikes_makes_name :selected").val()
    make = "0"  if make is ""
    jQuery.get "/quotes/update_model_select/" + make, (data) ->
      $("#bikeModels").html data

    false


$(document).ready(ready)
$(document).on('page:load', ready)
4

1 回答 1

0

我通过更改'shared/model_questions_fields'为:

<%= form_for('quote', remote: true) do |f| %>
    <%= f.fields_for :bikes do |g| %>
        <%= g.fields_for :models do |i| %>
            <%= i.label :name, 'Model' %>
            <% if !current_models.blank? %>
                <%= i.collection_select :name, current_models, :id , :name, include_blank: true %>
            <% else %>
                <%= i.collection_select :name, [], :id , :name, include_blank: true %>
            <% end %>
        <% end %>
    <% end %>
<% end %>
于 2013-10-16T04:14:40.820 回答