Help Inspire
Help Inspire

Reputation: 366

Create Simple Rails Filter for a Table

Newest version of Rails.

I have a table Positions that contains several columns, but the one in question is 'status'. This is a string based column that holds values 'Add' 'Error' 'Drop'. I have the table rendering in a view and wish to create links that will filter the data returned in the table, limited by status.

Add | Error

ID | Name | Status
1    Bob    Add
2    Jim    Error

If I clicked the Add link above the table in the view it will change the data in the table to only show Bob, since he has a status of Add. If I clicked Error link it will only display Jim.

I can currently limit the view data with @positions = Position.where(:status => "Add") but I want to invoke this limit upon link click.

Thanks for the help and if I need to define further please let me know.

Upvotes: 0

Views: 840

Answers (3)

beaorn
beaorn

Reputation: 454

Add link_to links that pass their respective status as params, then adjust that controller action and return @positions based on params[:status] if it is present.

Link

link_to "Error", positions_path(:status => "Error")

Controller

if params[:status].present? 
  @positions = Position.where(status: params[:status])
else
  @positions = Position.all
end

Upvotes: 2

gabrielhilal
gabrielhilal

Reputation: 10769

In the view, you can do something like:

link_to "Add", your_path(status: "Add")
link_to "Error", your_path(status: "Error")

Where your_path is the path to the controller/action you are doing the filter. In that controller do the following:

@positions = Position.where(:status => params[:status])

Upvotes: 0

MurifoX
MurifoX

Reputation: 15109

You can do exactly as described here in this answer: https://stackoverflow.com/a/3027233/1023609

Create a form with 2 submit buttons or more. In your action you use the submitted value from the params hash to make your query and change the list.

Upvotes: 1

Related Questions