Search code examples
ruby-on-railsrubycontrollers

Why two model objects are created in the new and create function in the controller class in ruby on rails instead of using just one?


Here I have a piece of code from a Controller class that I don't quite understand.

I see that a new Article object is created in the new method and is passed to the corresponding view where it is used by the form.

But I don't understand why another Article object is created in the create method with the parameter passed from the form instead of just using the same object that was instantiated in the new.

(Please note that I am new to Ruby on Rails and am coming from the object oriented world of Java ,and C++. So, I am really concerned about object referencing and stuff)

# GET /articles/new

  def new

    @article = Article.new

  end


  # POST /articles

  # POST /articles.json

  def create

    @article = Article.new(article_params)

    respond_to do |format|
      if @article.save
        format.html { redirect_to @article, notice: 'Article lll was successfully created.' }
        format.json { render :show, status: :created, location: @article }
      else
        format.html { render :new }
        format.json { render json: @article.errors, status: :unprocessable_entity }
      end
    end
  end

Solution

  • Because in traditional web development, HTTP is stateless. Each request starts anew. Therefore instance variables won't survive across requests.