Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby on Rails 5 Basics Adding a Model Attribute Updating Strong Parameters

Vincenzo Pace
Vincenzo Pace
2,886 Points

Why can Pet's constructor receive a function in the create method?

In the create method we call Pet.new(pet_params), which is a private method defined below. But we defined the new method without expecting any parameters.

app/controllers/pets_controller.rb
class PetsController < ApplicationController

  def new
    @pet = Pet.new
  end

  def create
    @pet = Pet.new(pet_params)
    @pet.save
    redirect_to pets_url
  end

  private

    def pet_params
      params.require(:pet).permit(:name, :birthdate, :breed)
    end

end
app/views/pets/_form.html.erb
<%= form_for(pet) do |f| %>

  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>

  <div class="field">
    <%= f.label :birthdate %>
    <%= f.date_select :birthdate %>
  </div>

  <div class="field">
    <%= f.label :breed %>
    <%= f.text_field :breed %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

1 Answer

Ari Misha
Ari Misha
19,323 Points

Hiya there! In Rails controller classes , the new action is mostly about creating a new fields/photos/profile, but we dont pass any parameters to our new @pet instance. Lets just dive deep about initializing a class. Pet class is simply a Ruby class implementation , which takes care of your Model (Data Layer). Being a class , we can easily instantiate it anywhere we want, right? If we get in the console , hit pet = Pet.new in the terminal, this will create a SQL query and the resultant hash will have null and default values on the fields that you defined in your migration classes, right? That being said, the same instance was store in an instance variable @pet. Now @pet is available in your view which is a form and im guessing it is rendering the partial _form.html.erb. Your @pet variable will pre populate the form with default values, isnt that whatchu want?

~ Ari

Vincenzo Pace
Vincenzo Pace
2,886 Points

Hi, thanks for your answer. Somehow I didn't notice that we are in the controller class, but thought we are in the Pet class. After your explanation everything is clear to me now, so again, thank you a lot!