创建帖子时如何访问参数
这意味着,在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Ruby 中,数字
0
和字符串"0"
在布尔上下文中都不会计算为false
。尝试if (params[:post][:agree]=="1")
In Ruby, neither the number
0
nor the string"0"
evaluates tofalse
in a boolean context. Tryif (params[:post][:agree]=="1")
Rails 默认情况下会创建一个复选框(使用
value="1"
)和一个隐藏的输入元素(使用value="0"
),因此您始终会获得一个值传回服务器,我个人认为这是愚蠢的并覆盖它。尝试检查params[:post][:agree].blank?
是否正确。但我不完全确定我理解你的整个问题。您只谈论表单数据,还是谈论您的模型?
Rails, by default creates both a checkbox (with
value="1"
) and a hidden input element (withvalue="0"
), so you always get a value passed back to the server, which personally I think is silly and override it. Try checking ifparams[: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?