1

As far as I understand we use namely an instance variable in the method new

def new
  @article = Article.new
end

because this variable is used in new.html.erb too. (Please correct me if I am wrong).

But why do we use an instance variable in the create method? Where else is it used outside the create method? Can't we just use a local variable article instead of the instance variable @article?

def create
  article = Article.new(article_params)

  if article.save
    flash[:success] = "Article created successfully!"
    redirect_to  articles_url
  else
    render 'new'
  end 
end

private  
def article_params
   params.require(:article).permit(:title, :body)
end

2 Answers 2

3

This means that you don't understand render :new.

This line means that the view for the new method will be rendered, but the method itself will NOT be invoked. That's why you need the variable to be instance variable, because if the validations fails, you will need it to pass it to form.

Take a look at the guides for more information

PS render :new is the same as render 'new'

Sign up to request clarification or add additional context in comments.

Comments

1

You can't, because @article variable is also used in new.html.erb file, rendered when article isn't saved successfully.

So you'll get (as far as I remember) error undefined method 'model_name' for nil:NilClass.

1 Comment

Yeah, you are right. It is used by new. I've just figured out it, when my rspec-test failed and so it rendered the new. Since I used a local version of article it ended up with an error message. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.