In Rails, why we use form_for @story do | f | when there is no loop?
we use
(1..10).each do |i|
p i
end
so that the value is "yield" for i in the block ...
but what about
<% form_for @story do |f| %>
<%= f.text_field :name %>
<% end %>
no loop at all ... why do we need to make it look like a loop? Can't we do this without making it look like a loop? (write differently)?
Also, need to use a Story instance here? Can't we use: history and achieve the same result? The @story instance has just been instantiated and has no data at all - does this really help create the form? Can't: history is enough? thanks.
Update:
- an idea like: (pseudocode only)
with_model_give_form (@story) do |f|
f.begin_form
f.text_field :name
f.end_form
end
so I think the block method will preserve begin_form and end_form because it automatically adds start and end before and after the block is called. what's the main advantage?
a source to share
I think you misunderstood how Ruby works in this case.
It is true that you are putting everything in a block, but that has nothing to do with the loop.
What are you actually doing in
(1..10).each do |i|
p i
end
creates a block {|i| p(i); }
and dispatches it to functionsRange.each()
It's the same with form_for
. In fact, you create a block {|f| puts( f.text_field(:name)); }
and pass it to the form_for function. (now it doesn't use puts, but some string concatenation, but you get the idea).
So, this is basically not a loop but a lambda function that will be called multiple times when called in a loop.
Here's some more information about blocks
Update: Regarding your update. In a way, yes, this is the main advantage. It's not entirely true, but you get the idea. The purpose of this block (and more) is to make the code easier to read and understand. And also speed up development.
Block dividing code has always been searched for, just take a look at the concept of functions, classes and other operators.
for example, it form_for
is mainly used to speed up development. Yes, it creates start and end tags, but that's not all.
<% form_for @story do |f| %>
<%= f.text_field :name -%>
<% end %>
In fact, something like:
<form action="<%= polymorphic_edit_path(@story) -%>"
id="<%= @story.class_name.underscore -%>">
<%= text_field :story, :name -%>
</form>
of course this is not entirely true, it makes it much easier and the function form_for
can do a lot more, but at least you should get an image.
a source to share
"Exit" does not always mean a loop - it is more of a "block" concept, but simply appears in most of the iterative / outline context. The more you think about income being the loop of the cycle, the more you feel and don't allow yourself to really explore the awesomeness of blocks.
As for: the story, yes, it's a little lame. You might think that Rails would just stabilize it and infer its model from there. You can also just Story.new in your opinion and do it in your controller, but yes, it's the same.
a source to share