简体   繁体   中英

Checkbox that will search DB for boolean - Rails 4

I have a search form and I need a checkbox that will select and then return whether a particular listing allows pets. I have created a custom route, controller method, and erb in the view. However, I am not accomplishing what I set out to do.

When a user clicks the Pets Allowed checkbox and then clicks search, the listings where pets allowed == true should be returned. I am not sure how to go about that.

This is the current code, but does not accomplish what I am after. This will redirect to /pets_allowed but that isn't a real thing.

listings_controller:

def pets_allowed
  @listings = Listing.where(pets: true)
end

routes.rb:

get "pets_allowed" => "listings#pets_allowed"

html.erb:

<div>
  <%= link_to 'Pets Allowed', pets_allowed_path, :class => 'button btn-transparent' %>
</div>

You probably need to use form_for instead of link_to .

<%= form_for :search_pets, url: pets_allowed_path, method: :get do |f| %>
  <%= f.check_box :has_pets %>
<% end %>

Now in action,

def pets_allowed
  @listings = Listing.where(pets: params[:search_pets][:has_pets])
end

When the checkbox is unchecked, it will return all the listings with no pets and when its checked it will return all the listings that have pets.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM