Rails:如何将自定义参数传递给控制器​​方法? [英] Rails: How do I pass custom params to a controller method?

查看:42
本文介绍了Rails:如何将自定义参数传递给控制器​​方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Rails 还很陌生.

I am fairly new to Rails.

我想跟踪帖子的阅读频率,以便按受欢迎程度对其进行排名.因此,我将在 posts 表中有一个数据库列 read_count ,每次调用 #show 时都会增加 1.

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.

但是,如果管理员已登录并希望通过 #show 方法预览帖子,我不希望 read_count 增加.

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.

我认为在 params 散列中传递一个自定义参数,例如 preview=true 是最好的.然后,如果 preview 评估为 false 或 nil,#show 只会增加 read_count.但是,我该怎么做?将 preview=true 添加到 params 哈希的正确方法是什么?

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?

或者在控制器上实现#preview 方法会更好吗?

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

推荐答案

以下答案之一可能是更好的方法,但要回答您关于如何传递额外参数的问题.您可以将它们添加到 url helper 的末尾,因此如果您现有的链接如下所示:

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)

link_to 'Show', post_path(id)

只需将其更改为:

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

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

这篇关于Rails:如何将自定义参数传递给控制器​​方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆