Reputation: 1841
I have a Rails 4 application and am trying to pass params[:search] captured from a form to the controller and ultimately to a js.erb file but the value of the hash is not going through.
sessions_controller.rb:
def home
@persons = People.select("persons.name").where("persons.name LIKE ?", params[:search])
respond_to do |format|
format.html
format.js { render :template => 'sessions/home.js.erb' }
end
end
home.html.erb:
<%= @persons.to_sql %>
<%= form_tag home_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>
<div id="persons">
</div>
_person_list.html.erb:
<%= person.name %><br>
home.js.erb file:
$('#persons').html("<%= escape_javascript(render partial: 'person_list', collection: @persons, as: 'person') %>");
console.log("<%= @persons.to_sql %>");
home.html.erb yields the following SQL snippet (which is expected):
WHERE (persons.name LIKE 'john')
But, from the code in the js.erb file, the developer console yields the following:
WHERE (persons.name LIKE NULL)
If I replace params[:search] in my controller with 'john' or if I set params[:search] = 'john', then the view file and js.erb file yield the same SQL snippet. Also, if I leave off the .where statemnt in the controller, the code works as well and I believe that the problem has something to do with using the params[:search]. Using the code above, I can confirm that the url contains:
www.website.com/home?search=john
and that the debug container shows:
--- !ruby/hash:ActionController::Parameters
utf8: ✓
search: john
controller: sessions
action: home
I've tried params[:search].to_s but that doesn't seem to work either.
Can somebody tell me how to pass the value of params[:search] to the js.erb file? Thanks!
Upvotes: 0
Views: 838
Reputation: 4296
Use the Network panel in your browser's developer tools to inspect the AJAX request you're making to the .js.erb
view. I think you'll find you're not passing a value for the search
parameter.
If the fix for your JavaScript isn't obvious, go ahead and add that to your question and we can help you debug it.
Upvotes: 2