Rails:form_for中的隐藏字段不向控制器发送参数
我有一个form_for
我在我的视图助手中制作,这将让一个用户从一个组中提升另一个用户。
def promote_button_for(group, user) membership = group.get_membership( user ) form_for membership, :url => group_membership_path( group, membership ) do |f| f.hidden_field :group_creator hidden_field_tag 'test', '1' f.submit( "Promote", :onclick => "return confirm(\"Are you sure you want to promote #{user.email} to an officer?\")" ) end end
当我通过按钮提交表单时,我似乎没有将任何隐藏的字段参数发送到控制器。
Started POST "/groups/1/memberships/6" for 127.0.0.1 at 2011-02-01 01:45:32 -0600 Processing by MembershipsController#update as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"VQl/rVX8OVOETv2HE7KtopUc3B19ShoMkUhjJwNlaZs=", "commit"=>"Promote", "group_id"=>"1", "id"=>"6"}
生成的Html看起来像:
任何帮助将不胜感激,
谢谢!
您遇到此问题是因为form_for
对象只看到最后一个f.submit
标记生成的字符串,而form_for
和f.submit
之间的所有其他内容都丢失了。
在这种情况下, form_for
标记不会直接操作视图,因为它基本上只是从promote_button_for
方法返回的字符串。
答案是你只需要将生成的标签链接在一起,如下所示:
def promote_button_for(group, user) membership = group.get_membership( user ) form_for membership, :url => group_membership_path( group, membership ) do |f| f.hidden_field(:group_creator) << \ hidden_field_tag('test', '1') << \ f.submit( "Promote", :onclick => "return confirm(\"Are you sure you want to promote #{user.email} to an officer?\")" ) end end
注意<< \
,它将所有生成的字符串连接在一起并将它们返回到form_for
。
你能试一下吗
f.hidden_field :group_creator, {:value => ''}