Rails: How do I pass custom params to a controller

2020-04-21 06:35发布

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?

3条回答
祖国的老花朵
2楼-- · 2020-04-21 06:59

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'

查看更多
Juvenile、少年°
3楼-- · 2020-04-21 07:02

What about doing something like:

@post.read_count.increment! unless user_signed_in? && current_user.admin?
查看更多
神经病院院长
4楼-- · 2020-04-21 07:20

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.

查看更多
登录 后发表回答