创建帖子时如何访问参数

发布于 2024-11-26 19:57:27 字数 497 浏览 0 评论 0原文

这意味着,在 PostsController def create 中,我想访问在布尔值一致的列中传递的值。创建帖子时,有一个复选框可以设置该值。选中则同意为真 (1),未选中则同意为假 (0)。现在我有代码 params[:post][:agree] 来访问这个值,但这似乎不起作用。 当我尝试在 if 语句中使用它时,该语句总是出现,就好像 params[:post][:agree] 总是评估为 true。

帮助!为什么这不起作用?

:编辑:

Post.rb(Post模型)

 attr_accessor :agree
 attr_accessible :agree

PostController(默认创建)

@post.title = "AGREED!!" if params[:post][:agree] == "1"

Meaning that, in PostsController, def create, I want to access the value that is passed in the column for the boolean value agree. When creating a post, there is a checkbox that sets this value. Checked makes agree true (1) and unchecked makes agree false (0). Right now I have the code params[:post][:agree] in order to access this value, but that doesn't seem to work.
When I try to use that in an if statement, the statement always occurs, as if params[:post][:agree] always evaluates to true.

Help! Why doesn't this work??

:EDIT:

Post.rb (Post Model)

 attr_accessor :agree
 attr_accessible :agree

PostController (In def create)

@post.title = "AGREED!!" if params[:post][:agree] == "1"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白芷 2024-12-03 19:57:27

在 Ruby 中,数字 0 和字符串 "0" 在布尔上下文中都不会计算为 false。尝试 if (params[:post][:agree]=="1")

In Ruby, neither the number 0 nor the string "0" evaluates to false in a boolean context. Try if (params[:post][:agree]=="1")

画离情绘悲伤 2024-12-03 19:57:27

Rails 默认情况下会创建一个复选框(使用 value="1")和一个隐藏的输入元素(使用 value="0"),因此您始终会获得一个值传回服务器,我个人认为这是愚蠢的并覆盖它。尝试检查 params[:post][:agree].blank? 是否正确。

但我不完全确定我理解你的整个问题。您只谈论表单数据,还是谈论您的模型?

Rails, by default creates both a checkbox (with value="1") and a hidden input element (with value="0"), so you always get a value passed back to the server, which personally I think is silly and override it. Try checking if params[:post][:agree].blank? instead.

I'm not entirely sure I understand your entire question though. Were you only talking about the form data, or are you talking about your models?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文