1

Quick beginner question about new and create methods. The Ruby Guide shows this example:

def new
  @article = Article.new
end

def create
  @article = Article.new(article_params)

  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end

In a different example in the guide, the statement @article = Article.new was not used in the new method, which makes more sense to me. The new view doesn't need @article, the form_for takes a parameter of the model name, then defines a variable for the form methods to use inside the |something|. So why do we need to establish @article = Article.new and have @article available for the view?

inthenameofmusik
  • 617
  • 1
  • 4
  • 16

3 Answers3

1

You are writing a form to "create" an Article, the article class might have some default values that you may want to show in the form, in this way you don't have to take care of it in the view itself.

Also in this way, whatever default you have, it's in the same location, you don't need to update two files.

Francesco Belladonna
  • 11,361
  • 12
  • 77
  • 147
1

Below both are equivalent -

1. form_for(@article...........) /* @article = Article.new */
2. form_for(:article...........)

For more details see http://apidock.com/rails/ActionView/Helpers/FormHelper/form_for

But, in Rails, we write DRY code. So, we are using same article_form and instance variable @article for new and edit method and yes, this instance variable available in view -

def new
  @article = Article.new /* this is new article */
end

def edit
  @article = Article.find params[:id] /* Already exists in database */
end

and view file -

new.html.erb and edit.html.erb have same form

 <%= render "article_form" %>
Amit Suroliya
  • 1,515
  • 1
  • 11
  • 21
1

According to the documentation (http://guides.rubyonrails.org/form_helpers.html#binding-a-form-to-an-object) your form (if created with form_for) needs an instance of a model to bind the input to the model attributes. In this way you are saying that you have a new article instance and your form fields maps to its attributes, so when the form is submitted, you receive the params in the form of:

articles: {attributte1: 'something', attributte2: 'somethingelse'}

This way you can populate an instance of an object by saying @article = Article.new(article_params), as article_params is populated inside your controller somewhere.

MurifoX
  • 14,991
  • 3
  • 36
  • 60