def new
@post = Post.find(params[:post_id])
@comment = @post.comments.build
end
instead of:
def new
@comment = Post.find(params[:post_id]).comments.build
end
is the 2nd style possible? If no, why not?
if yes, why is the 1st style preferred?
Depends on your view code. Remember that controller @instance variables
are copied to the view, so that the first example would make both @post
and @comment available in the view, whereas the second example would
only make @comment available.
why is this required:
def new
@post = Post.find(params[:post_id])
@comment = @post.comments.build
end
instead of:
def new
@comment = Post.find(params[:post_id]).comments.build
end
is the 2nd style possible? If no, why not?
if yes, why is the 1st style preferred?
Depends on your view code. Remember that controller @instance variables are copied to the view, so that the first example would make both @post and @comment available in the view, whereas the second example would only make @comment available.
And of course if you just had @post you could easily extract comments
in the view code by @post.comments.build. @comment is really not
necessary because @post gives you the handle you need.