In LessonsController, there are new and create methods.
def new
@lesson = Lesson.new
end
def create
@lesson = Lesson.new(params[:lesson])
if @lesson.save do something end
end
I’ve been doing this in my apps without giving a thought. It works, but I’m confused why I am creating the instance variable both in the new and create action. From what I understand, this is the flow:
When a user clicks the new lesson button, he will be directed to LessonsController#new. When he puts in the required value and click submit he will be directed to LessonsController#create. I haven’t needed a view template for the create method.
So my confusion is, why are you creaing @lesson object again in the create method? I think the answer to this question might have to involve some concepts about GET and POST HTTP methods as well.
I appreciate any help! Thank you.
This is because HTTP is a sessionless protocol and any instance variables are not carried over between multiple requests.
A request to load up the
#newpage is a single request and once you submit the form and hitcreatebutton (or any of it’s other counterpart) The browsers initiates a new request to your#createmethod.The first time around in
#newmethod – You are creating an instance variable@lessonwith it’s default values:@lesson = Lesson.newHowever, the second time around in
#createmethod – The new request is forcing to create a very different instance variable:@lessong = Lesson.new(params[:lesson])This ^ second time around you are initiating the instance variable with the values received from the form submit (usually a
POSTrequest with#create). I hope that clears any air with why it is this way.