UserDuser
UserDuser

Reputation: 461

Rails 4 use of non-model attributes in params resulting in undefined method `merge' for nil:NilClass

I have a search form on an index page for my Properties model which is using both Ransack and Geocoder to search the Properties model fields as well as narrow the results down based on distance from an address input by the user in the search form.

The address and distance are captured in the form with :nearaddress and :distance, respectively, which I send in params[:near]. I am checking for the presence of them in the controller index action following this answer. The result is “undefined method `merge' for nil:NilClass” when navigating to /properties, so the view will not render. How do I enable these non-model form parameters to be passed to the controller properly? I think this might be a strong parameters issue but I'm stuck on how to permit these attributes that aren't in the Properties model. The error highlights the "f.text_field :nearaddress" line.

index.html.erb:
...form fields that work when excluding the two that follow...
<div class ="field">
  <%= f.label :nearaddress, "Address" %>
  <%= f.text_field :nearaddress, params[:near] %>
</div>
<div class ="field">
  <%= label_tag :distance %>
  <%= text_field_tag :distance, params[:near] %> miles
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>

properties_controller.rb:
def index
if params[:near].present? && (params[:near].to_i >0)
  @search = Property.near(params[:near]).search(params[:q])
else  
  @search = Property.search(params[:q])
end
  @properties = @search.result(:distinct => true).paginate(:page => params[:page])
  ...
end

Upvotes: 0

Views: 824

Answers (1)

UserDuser
UserDuser

Reputation: 461

I was able to resolve this problem by removing the "f." and adding "_tag" to the :nearaddress field as well as specifying the params in the controller index:

<%= label_tag :nearaddress, "Near Address" %>
<%= text_field_tag :nearaddress, params[:near] %>
<%= label_tag :distance, "Distance From Address (mi)" %>
<%= text_field_tag :distance, params[:near] %>
<div class="actions"><%= f.submit "Search" %>
<% end %>

if params[:distance].present? && (params[:distance].to_i >0) && params[:nearaddress].present?
  @search = Property.near(params[:nearaddress],params[:distance]).search(params[:q])
else  
  @search = Property.search(params[:q])
end

Upvotes: 0

Related Questions