Ruby-on-rails 通过 rails 3 中的表单发送额外的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6000069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send an extra parameter through a form in rails 3
提问by Elliot
Is there a way to send an extra parameter through a form in rails 3?
有没有办法通过 rails 3 中的表单发送额外的参数?
For example:
例如:
<%= form_for @post do |f| %>
<%= f.hidden_field :extraparam, :value => "22" %>
<% end %>
but lets say :extraparam isn't part of the post model..
但可以说:extraparam 不是后期模型的一部分..
I have an unknown attribute error in the create method of the controller when I try this, any ideas?
当我尝试这个时,控制器的创建方法中有一个未知的属性错误,有什么想法吗?
(I want to use the param value itself in the controller for some extra logic)
(我想在控制器中使用参数值本身来实现一些额外的逻辑)
回答by Paul Rosania
Call hidden_field_tagdirectly. See: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-hidden_field_tag
hidden_field_tag直接打电话。请参阅:http: //api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-hidden_field_tag
These helpers exist for all the major form field types, and are handy when you need to go beyond your model's methods.
这些助手适用于所有主要的表单字段类型,当您需要超越模型的方法时非常方便。
回答by ConorB
The following worked for me in passing extra parameters from the view back to the controller that were a part of my model and not part of my model.
以下对我来说,将额外的参数从视图传递回控制器,这些参数是我的模型的一部分,而不是我的模型的一部分。
<%= hidden_field_tag :extraparam, value %>
Example usage
示例用法
<%= hidden_field_tag :name, "John Smith" %>
回答by Branden Silva
Ya Paul is right. Hidden_field is associated with your model whereas the extra _tag fields are not. I'm not sure of your needs but It's generally recommended in the RoR community to avoid passing a ton of hidden_fields like you might do in a php application.
雅保罗是对的。Hidden_field 与您的模型相关联,而额外的 _tag 字段则没有。我不确定您的需求,但 RoR 社区通常建议您避免像在 php 应用程序中那样传递大量 hidden_fields。
Ive seen some code where ids were getting passed around in hidden fields which rails takes care on its own if you know the best practices and take full advantage of the framework. Of course I'm just saying this as general info as there are sometimes better ways at accomplishing the same functionality. Good luck on your apps.
我见过一些代码,其中 id 在隐藏字段中传递,如果您了解最佳实践并充分利用该框架,rails 会自行处理。当然,我只是说这是一般信息,因为有时有更好的方法来完成相同的功能。祝你的应用程序好运。

