Kevin K
Kevin K

Reputation: 2227

Passing boolean parameter to rails controller?

I have a post object with a boolean called :published. The the definition for index in the controller looks like this:

def index
  @posts = Post.all

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @posts }
  end
end

And this links to that page:

<%= link_to 'All posts', posts_path %>

Let's say instead I want the option of showing only posts where post.published? is true.

Upvotes: 4

Views: 4873

Answers (2)

Christian Fazzini
Christian Fazzini

Reputation: 19713

In theory, for filtering results by keywords / categories, it is fine to display the logic in the same controller via a param. I would have it as:

<%= link_to 'All posts', posts_path(:published => true) %>

Then in your controller / index action:

def index
  @posts = Post.all
  @posts = @posts.where(:published => true) if params[:published].present?
  ...

To refactor your code, I would scope the method in the model, with something like:

scope :published, where(:published => true)

Then in your controller you can just have:

@posts = @posts.published if params[:published].present?

For more information on chaining / model scopes: http://guides.rubyonrails.org/active_record_querying.html#scopes

Upvotes: 3

Scott McMillin
Scott McMillin

Reputation: 531

To keep it really simple (no scopes), just do the following

def index
  @posts = if params[:published].present?
    Post.where(:published => true)
  else
    Post.all
  end
...

And then to add the link with params do

%= link_to 'Published Posts', posts_path(:published => true) %>

Upvotes: 2

Related Questions