Passing boolean parameter to rails controller?

controller, parameter-passing, ruby-on-rails

Solution

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) %>

Problem

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. - Should I have a separate method in the controller to handle the case where only :published posts would be shown? - Can I alter the index method to handle a parameter being passed to it? - What would the link_to look like?

Original source