I've been struggling with this issue for weeks and haven't been able to find or figure out a solution. Here is what I'm trying to accomplish: a form that is automatically populated with a list of questions based on user input. Specifically, I have a list of all possible questions (PossibleQuestion model) that I want to use to populate the form based on the site a user selects.
I know I'm not rendering a proper response to the ajax request. I'm currently getting an undefined local variable or method f
error. I found several SO questions regarding passing the form builder (here and here), however none of them have helped.
I'm still new to ruby and rails, so any help or direction is greatly appreciated!
Versions (ruby 2.3, rails 4.2.2). Also using SimpleForm and Cocoon gems.
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 } %>");
I've tried passing the formbuilder object f
here in locals, however it doesn't work. I get an error that f is undefined.
_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 %>