Mirror318
Mirror318

Reputation: 12673

Why do I create a new model object in two methods in a controller?

Following various parts of the internet, I have the following code:

Controller

class StudiesController < ApplicationController

    def new
        require_user
        @study = Study.new
    end

    def create
        @study = Study.new(study_params)
        if @study.save
            flash[:success] = "You made it!"
            redirect_to root_path
        else
            flash[:danger] = "Uh oh—something went wrong"
            redirect_to study_path
        end
    end
end

View

<%= form_for(@study, url: {action: :create}, class: "study-form") do |f| %>
    <%= f.text_field :title %><br>
    <div class="btn-submit">
        <%= f.submit "I studied today!", class: "btn btn-primary margin-top" %>
    </div>
<%= end %>

It works, but my question is: Why do I need Study.new called twice? Why do I call it in create if I've already called it in new?

Upvotes: 0

Views: 558

Answers (2)

David Aldridge
David Aldridge

Reputation: 52346

The instance of Study that is created in the new method is used in the view to render HTML.

When that HTML is sent to the browser, the instance of Study no longer exists -- it was never saved, and was created just to help render the HTML.

When a form is submitted from the browser, parameters are passed in to assign values to the instance that is to be created, but first a new instance of Study must be created to assign them to.

This instance is then saved.

Upvotes: 2

Bhushan Jadhav
Bhushan Jadhav

Reputation: 21

When you are using Study.new in the new method to create a new object, it is used to create a new record before saving and to render a new form. After that when you are using Study.new(study_params) in a create method it will built object from values submitted by the form and the data will be saved in the database table.

Upvotes: 1

Related Questions