why strong parameters for the CREATE, but not NEW, in a rails controller?

Refresh

February 2019

Views

549 time

1

I am confused as to why, in an example Articles Controller, the create method is utilizing strong parameters, but the new method isn't?

   def new
        @article = Article.new
    end

    def create
        @article = Article.new(article_param)
        if @article.save
            redirect_to @article
        else
            render "new"
        end
    end

3 answers

3

Because strong_parameters are there for whitelist params before update or create a record. While on new or edit action there are not any action over db records, and it isn't necessary to whitelist any params. On update and create controller actions there are action over the db, and any parameters that is not whitelisted is forbidden.

Also rails guides show the same definition: "With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted. This means you'll have to make a conscious choice about which attributes to allow for mass updating and thus prevent accidentally exposing that which shouldn't be exposed."

The most common example is when: In your browser you can edit a field name and change <input name=user[name] ...> to <input name=user[admin] ...> then at the form change value to '1' and submit. Without strong parameters user[:admin] is a valid parameter and get changed at the database. Further, at the new or edit action, there are no risk of any impact on the db, because you are only sending a form to the browser.

1

The new method just instantiates a new object. The create method is responsible for assigning the attributes and writing them to the database.

After calling .new, your article is just an empty shell, therefore no params are needed.

The new article is used so the page can render the proper form. Also, on the new action there aren't any params in the controller, the user has simply clicked a new button so they can receive the view to create the new article.

Your params represent user entered data and aren't there until after the form is submitted.

0

The new method is the Form itself where the data is inputted by the User. It is submitted through the create method which is where your app will recognize the specifications of your form and will accept or reject elements inputted by the User. For example if you have an integer assigned to a table element and a User input a float/decimal into your form the new form will accept the input but actually only create an integer without a decimal for that number inputted when it is rendered in the views.