rails - hidden_​​field 和 hidden_​​field_tag 到底是做什么的? [英] rails - what exactly does hidden_field and hidden_field_tag do?

查看:58
本文介绍了rails - hidden_​​field 和 hidden_​​field_tag 到底是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通读了 hidden_​​fields 的技术性定义,但不确定它到底是做什么的.我的理解是它允许您为某些参数传入一个属性.例如,如果您有丰富的联接模型,则可以使用 hidden_​​field 将 user_id 分配给用户的联接模型属性.对吗?

I read through the techy definition of hidden_fields, but am not sure what it really does. My understanding is that it allows you to pass in an attribute for certain parameters. For example, if you have a rich join model, you can use the hidden_field to assign the user_id to the join model attribute for user. Is that correct?

如果是这样,是在表单中还是在控制器中进行更好?

If so, would it be better to do it in the form or the controller?

推荐答案

这两种方法都是创建隐藏"类型的 HTML 输入标签的助手,是的,它们用于向请求添加参数(通常是表单 POST).实际上,参数可以是您想与请求一起发送的任何信息.不过要小心,因为隐藏字段很容易被篡改.

Both of those methods are helpers to create an HTML input tag of type "hidden", and yes, those are used to add parameters to a request (typically a form POST). Really the parameter can be any piece of information you want to send along with a request. Be careful, though, as hidden fields are easily tampered with.

这是一个将在隐藏字段中发送用户 ID 的示例

Here's an example that will send a user id in a hidden field

# Form
<%= form_tag foo_path do %>
  <%= hidden_field_tag "user_id", @user.id %>
  ....
  <%= submit_tag "Click Me" %>
<% end %>

# Controller
def foo
  # params[:user_id] is set with the value from the hidden field
  # Do useful stuff with the POST data
end

虽然你可以像这样传递诸如 user_id 之类的东西,但我发现很少需要它.如果在给定情况下始终需要 user_id,您可以考虑使用嵌套路由 http://guides.rubyonrails.org/routing.html#nested-resources.

While you can pass things such as user_id's like this, I find that the need for it is rare. If a user_id is always required for a given situation you might consider using nested routes http://guides.rubyonrails.org/routing.html#nested-resources.

这篇关于rails - hidden_​​field 和 hidden_​​field_tag 到底是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆