I am following this tutorial http://guides.rubyonrails.org/v3.2.13/getting_started.html to build my rails app in version 3.2.13 . If you go to the section 6.9 you will find controller and view for creating new posts . Here I do not get how @post
variable is passed from new
action to create
action and where is create
function called ? Also , I faced the same problem while working on edit
and update actions
. Please guide me through this .
问题:
回答1:
It's not passed to create
action, it's instantiated again with params you pass from the form displayed with new
action.
create
action is called with POST request to the path specified in config/routes.rb, leading to specific controller and action.
回答2:
@post
is not passed from new
to create
the params
hash is passed into the create method @post
is then set using the new
method of the model not the controller. create
calls new
and then save
and returns the object. new
returns the object without saving and then save
returns the validity of the object. That is why the create method in the controller calls new
and then has a conditional statement for save
. It is basically saying initialize this object then if it is a valid object do one thing if it is not do another. The create action is not called because of this check.
#this will return true if valid or false if invalid
Post.new(params[:post]).save
#this will always return the Post object which conditionally is true in Ruby
Post.create(params[:post])
#To use the create in a conditional statement it would be
Post.create(params[:post]).valid? || Post.create(param[:post]).save
The last line is unnecessarily redundant and thus why the example uses new
followed by save
.
create
method for a Model is more succinct but probably best to use when you know the object is valid.
Hope this gives you a better understanding but if you are still confused please let me know and I will try to explain further.