user2664110
user2664110

Reputation:

Rails filter product listing based on attribute in controller

Rails newbie here. This specific question has probably been asked before, if not here then on some other site, but after looking around a lot I wasn't able to find anything helpful because I lack the terminology to describe what I want to accomplish. I'm sorry if it comes across as trivial.

Basically I have a freshly created Rails project with a scaffold Item (generated by rails g scaffold Item [...attributes...]) and I want to create an additional page, similar to the index page, but instead of displaying all of the items I want the items to be filtered. So for the index page the part in the controller file looks like this

def index
 @items = Item.all
end 

and I want to know how to, instead, have some sort of controller for my other page (call it index2) that uses some find-like method only grabs the Items that have a certain attribute, e.g. are "red" in color:

def index2
  @items = Item.find(color: "red") #all items that have red as their color attribute
end                                #are assigned to @items

How can I do this? And where can I find more manipulations (other than all(), first, second, ...) like this? Thank you for your patience.

Upvotes: 1

Views: 1305

Answers (1)

usha
usha

Reputation: 29349

You can add an action to your ItemsController

def red_items
  @items = Item.where(color: "red")
end

you can use where for all the filters

You will have to add a view called red_items.html.erb to /app/views/items for the controller to render automatically. If you want to use index template, then just render the template explicitly in your new action

def red_items
  @items = Item.where(color: "red")
  render :template => "index"
end

Here is a link to Active Record Query Interface where you can find all possible query methods

Upvotes: 1

Related Questions