0

As the title says, I am trying to load a form partial with an AJAX request; one of the fields in my form requires a variable in the controller so it can create the select dropdown menu. If I render the partial directly in the view, it accesses the variable fine but when I separate the partial and try to load it via an AJAX request, it doesn't know how to find the variable.

I have tried following the answer found here (giving it to the partial as a local variable) but it still does not work.

@headers is the variable that is not being loaded.

partial:

= simple_form_for(Constraint.new, html: {:multipart => true, autocomplete: "off", :class=> "form-horizontal" }, remote: true, :authenticity_token => true) do |f|
  div.profile-details
    br
    = f.select :header, @headers.each{|header|} , input_html:{:class => "user-update"}, label: "Header", :prompt   => "Select a Header"
    br
    = f.button :submit, "Save Constraint"

.js file that loads partial:

$(".newConditionContainer").append('<%= escape_javascript(render 'projects/rulesConstraintsInput')%>');

UPDATE:

I ended up defining the variable in the controller method that calls the js request. I had earlier assumed that the variable was accessible but it was only being defined in a method outside of the partial.

Community
  • 1
  • 1
Kyle Bachan
  • 1,053
  • 2
  • 15
  • 33

1 Answers1

0

Partials need to begin with an underscore so name it something like _partial_name.html.erb then you can reference a partial using render like this and pass any local variables you like

<%= render partial: "partial_name", locals: {headers: @headers} %>

Headers will be available as a local varaible inside the partial now. Just change @headers to headers

Cheers

user827570
  • 491
  • 1
  • 8
  • 15
  • This is the answer I tried and it still doesn't seem to work. My partial is in a separate file if that helps explain it. It just tries looking for the header variable and saying "NoMethodError - undefined method `each' for nil:NilClass". – Kyle Bachan Sep 15 '14 at 15:21
  • How is your .js file getting access to the @headers variable if its stored in your controller? – user827570 Sep 15 '14 at 15:36
  • That's essentially my question. What would be the best way to access that variable? – Kyle Bachan Sep 15 '14 at 15:38
  • 1
    Couple ways I can think of to do it. A hidden input element which you set the value to your headers var and use JS to retrieve it. Or you could use a templating engine like Handlebars.js, you'll be able to generate a section of reusable html and you can just feed it variables from the controller when you render the view. – user827570 Sep 15 '14 at 15:45
  • Thanks for your help--I ended up just defining said variable in the controller method that calls the js request. – Kyle Bachan Sep 15 '14 at 16:30