Passing a boolean parameter to a rails controller?

I have a post object with a boolean name: published. The definition of the index in the controller is as follows:

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

And these are the links to this page:

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

Say, instead, I want you to only show posts that posted post.published? truly.

  • Should I have a separate method in the controller to handle the case when only: posted messages will be displayed?
  • Is it possible to change the index method to handle the passed parameter?
  • What will link_to refer to?
+4
source share
2 answers

To make it really simple (no areas) just follow these

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

And then add a link with do parameters

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

Theoretically, to filter the results by keywords / categories, it is good to display the logic in the same controller through the parameter. I would like to have this as:

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

Then in the action of your controller / index:

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

To reorganize your code, I would apply a method in a model with something like:

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

Then in your controller you can simply:

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

Additional information about chains / models: http://guides.rubyonrails.org/active_record_querying.html#scopes

+3
source

All Articles