Question

After an afternoon spending in web search. I have to ask you.

In my app I have a list of games which have one or more platforms associated. I want to propose to the user some filter based on the platform.

I know that I have to use named scopes with an attribute. But I don't know how to make link which

Was it helpful?

Solution

If you use :has_and_belongs_to_many a lazy way to do this is get all plataforms and game a uniq array of all game:

@games = @plataforms.map(&:games).uniq

If you use :has_many:

# in your game model
scope :by_plataforms, lambda { |plataforms_ids| where(:plataform_id => plataforms_ids) }

A sample call: Game.by_plataforms([1, 2, 3])

EDIT

To create a route you can use a param in your GamesController to filter by plataform:

def index
  @games = params[:plataform] ? Plataform.find(params[:plataform]).games : Game.all
end

And in the views:

<%= link_to games_path(:plataform => @plataform.id) %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top