Trying to break apart Rails code more so I can understand what's happening
<%= form_for :article do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
This code is from 5.2 section of edgeguides: http://edgeguides.rubyonrails.org/getting_started.html
<%= form_for :article do |f| %>
That line is bothering me. Why is it a symbol instead of @article?
@article would be an instance of Article object, right? And wouldn't you want that for form_for?
ps. feel free to edit the title to be more reflective of this post.
EDIT ... I understand why this post is marked as duplicate, and I'm fine with letting that stand as.
However, I just had to post this. I don't know if this is me (ie, my error) or the fact that I'm dealing with Rails 4, but when I changed it from a symbol (:article) to object (@article) - I got this error when I refreshed the new page.
This is the error: First argument in form cannot contain nil or be empty
Just for clarification, this is the line I changed:
<%= form_for @article do |f| %>
No, not trying to change the question, or any of that. I had assumed initially when I wrote up this post, that either would work. But just for the heck of it, after reading the responses, I tried the @, and got that error.
So, wondering what's going on, or if it's just me?
Yes, your suspicion is correct, but you did not read far enough:
When you call form_for, you pass it an identifying object for this form. In this case, it's the symbol :article. This tells the form_for helper what this form is for. Inside the block for this method, the FormBuilder object - represented by f - is used to build two labels and two text fields, one each for the title and text of an article. Finally, a call to submit on the f object will create a submit button for the form.
There's one problem with this form though. If you inspect the HTML that is generated, by viewing the source of the page, you will see that the action attribute for the form is pointing at /articles/new. This is a problem because this route goes to the very page that you're on right at the moment, and that route should only be used to display the form for a new article.
The form needs to use a different URL in order to go somewhere else. This can be done quite simply with the :url option of form_for. Typically in Rails, the action that is used for new form submissions like this is called "create", and so the form should be pointed to that action.
TLDR
use form_for(@article || Article.new) do |f|
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With