Ruby-on-rails Rails隐藏字段未定义方法“合并”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6636875/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:33:34  来源:igfitidea点击:

Rails hidden field undefined method 'merge' error

ruby-on-railsrubyruby-on-rails-3formshidden-field

提问by Jake

I wanna do something like this in rails

我想在 Rails 中做这样的事情

Here is what I have so far in rails:

这是我迄今为止在 Rails 中的内容:

<%= form_for @order do |f| %>
  <%= f.hidden_field :service, "test" %>
  <%= f.submit %>
<% end %>

But then I get this error:

但是后来我收到了这个错误:

undefined method `merge' for "test":String

How can I pass values in my hidden_field in rails?

如何在 rails 中的 hidden_​​field 中传递值?

回答by apneadiving

You should do:

你应该做:

<%= f.hidden_field :service, :value => "test" %>

hidden_fieldexpects a hash as a second argument

hidden_field期望散列作为第二个参数

回答by user132447

You are using a hidden_field instead of a hidden_field_tag. Because you are using the non-_tag version, it is assumed that your controller has already set the value for that attribute on the object that backs the form. For example:

您使用的是 hidden_​​field 而不是 hidden_​​field_tag。因为您使用的是非 _tag 版本,所以假设您的控制器已经在支持表单的对象上设置了该属性的值。例如:

controller:

控制器:

def new
  ...
  @order.service = "test"
  ...
end</pre>

view:

看法:

<%= form_for @order do |f| %>
  <%= f.hidden_field :service %>
  <%= f.submit %>
<% end %>

回答by Tushar.PUCSD

It works fine in Ruby 1.9 & rails 4

它在 Ruby 1.9 和 rails 4 中运行良好

<%= f.hidden_field :service, value: "test" %>

回答by Michael Durrant

A version with the new syntax for hashes in ruby 1.9:

在 ruby​​ 1.9 中具有新的哈希语法的版本:

<%= f.hidden_field :service, value: "test" %>

回答by bradmalloy

This also works in Rails 3.2.12:

这也适用于 Rails 3.2.12:

<%= f.hidden_field :service, :value => "test" %>

<%= f.hidden_field :service, :value => "test" %>

回答by Alex Teut

By the way, I don't use hidden fields to send data from server to browser. Data attributesare awesome. You can do

顺便说一下,我不使用隐藏字段将数据从服务器发送到浏览器。数据属性很棒。你可以做

<%= form_for @order, 'data-service' => 'test' do |f| %>

And then get attribute value with jquery

然后用jquery获取属性值

$('form').data('service')