动态更新嵌套fields_for

时间:2016-11-28 01:58:56

标签: javascript ajax ruby-on-rails-4

我几周来一直在努力解决这个问题,而且无法找到或找出解决方案。以下是我要完成的内容:一个自动填充基于用户输入的问题列表的表单。具体来说,我列出了所有可能的问题(PossibleQuestion模型),我想根据用户选择的网站填写表单。

我知道我没有对ajax请求做出正确的回应。我目前收到undefined local variable or method f错误。我发现了几个关于传递表单构建器(herehere)的SO问题,但是没有一个有帮助。

我还是ruby和rails的新手,所以非常感谢任何帮助或方向!

版本(ruby 2.3,rails 4.2.2)。还使用SimpleForm和Cocoon宝石。

report.rb

class Report < ActiveRecord::Base
  belongs_to :site
  has_many :questions, :dependent => :destroy
  accepts_nested_attributes_for :questions, :allow_destroy => true
end

site.rb

class Site < ActiveRecord::Base
  has_many :reports
  validates :state, presence: true
end

question.rb

class Question < ActiveRecord::Base
    belongs_to :report
    has_many :answers, :dependent => :destroy
    accepts_nested_attributes_for :answers, :allow_destroy => true
end

possible_question.rb

class PossibleQuestion < ActiveRecord::Base
  validates :content, :state, presence: true
end

answer.rb

class Answer < ActiveRecord::Base
  belongs_to :question
end

reports_controller.rb

def new
    @report = Report.new
    @questions = PossibleQuestion.all
    @questions.each do |q|
        question = @report.questions.build
        question.content = q.content
        question.answers.build
    end
end

def questions_list
  @site = Site.find(params[:id])
  @state = @site.state
  @questions = PossibleQuestion.where(state: @state).to_a
  respond_to do |format|
    format.js
  end
end

report.js

$(document).ready(function() {
    $('#report_site_id').change(function() {
        site_id = $('#report_site_id').find(':selected').val();
        $.ajax({
                url: '/questions_list',
                data: { id: site_id, },

questions_list.js.erb

$(".questions").html("<%= j render 'question_fields', :locals => { :questions => @questions } %>");

我已尝试在本地传递formbuilder对象f,但它不起作用。我得到一个f未定义的错误。

_question_fields.html.erb

<%= f.simple_fields_for :questions do |builder| %>
  <%= f.label f.object.content %>
  <%= f.hidden_field :content, :value => f.object.content %>

  <%= f.simple_fields_for :answers do |builder| %>
    <%= render 'answer_fields', :f => builder %>
  <% end %>
<% end %>

_form.html.erb

<%= simple_form_for @report do |f| %>
  <%= f.association :site %>

  <div class="questions"></div>
<% end %>

0 个答案:

没有答案