Rails: How do I pass custom params to a controller

2020-04-21 07:15发布

问题:

I am fairly new to Rails.

I want to track how often a post is read in order to rank them in order of popularity. Therefore, I will have a database column read_count in the posts table which increments by 1 each time #show is called.

However, if an admin is signed in and wants to preview the post via the #show method, I do not want the read_count to increment.

I thought passing a custom param such as preview=true in the params hash would be best. Then, #show would only increment read_count if preview evaluated to false or nil. But, how do I do that? What's the correct way to add preview=true to the params hash?

Or would it be better to implement a #preview method on the controller?

回答1:

One of the below answers is probably a better way, but to answer your question of how to pass extra params. You can just add them to the end of your url helper, so if your existing link looks like:

link_to 'Show', post_path(id)

just change it to:

link_to 'Show', post_path(id) + '?preview=true'



回答2:

What about doing something like:

@post.read_count.increment! unless user_signed_in? && current_user.admin?


回答3:

Why not instead of sending a param you do it through the controller action itself? If it is hit and is not admin then increment the count, seems like a simpler solution.