Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

hidden field - rails - what exactly does hidden_field and hidden_field_tag do?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...