Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I used this gem in my application, but I'm not sure the difference between the different implementation options for the gem:

  • form_for
  • form_tag with block
  • form_tag without block

Can anyone clarify? I understand that form_for is used when you wish to interact with a model, but what about the other two?

See Question&Answers more detail:os

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

1 Answer

The differences are subtle, but important. form_for is a more advanced tool that yields an object you use to generate your form elements:

<% form_for(@foo) do |form| %>
  <%= form.text_field(:bar) %>
<% end %>

The form_tag method is much more primitive and just emits a tag. If you want to put things inside of the <form> tag that's emitted, you put things inside the block:

<% form_tag do %>
  <%= text_field_tag(:bar, 'bar_value') %>
<% end %>

Note that the form_for method handles grabbing values from your model, and will at least try to route the form to the appropriate action. With form_tag you are responsible for everything as it makes no assumptions about what you're doing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...