I'm new in Rails, and I'm trying to filter the animals I have on my DB, by one of their properties. I have read that I can make it by a scope in the controller, and have access to it by a parameter on the URL, but I think that doesn't work for me because I'm using a loop to create my HTML.
Is there a way to add a filter to the collection I'm using (@animals)?
<% @animals.each do |animal| %>
<li>
<a href="#">
<%=link_to animal.ncommon, animal %>
</a>
</li>
<% end %>
I hope I was clear with my question. Thank you for your help!
So the best practice is to move the scope
to the models , not in the controller. Here is and example. (please note that this may change depending on your file structure and names).
here I'm going to filter animals by type. Lets say type 1 and type 2.
#model app/models/animal.rb
class Animal < ActiveRecord::Base
scope :by_type, -> (ty) { where(type: ty) }
end
#controller app/controllers/animals_controller.rb
class AnimalsController < ApplicationController
... other code
def index
# calls the by_type method/scope in the Animal model
# filter the records and assignes them to @animals varaible
@animals = Animal.by_type(params[:type])
end
... other code
end
then you can use your loop in the view. When you want to filter, you call the index action with a parameter
Eg http://localhost:3000/animals?type=1
So the idea is, not to filter inside the loop, but to get the filtered results to the @animals
variable.
I just found a solution that i can use in the loop. I changed:
<% @animals.each do |animal| %>
to:
<% @animals.where("promo > ?", 0).each do |animal| %>
Here i´m getting all the animals that has a promo greater than zero.
Thanks!
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.