Reputation: 99
def new
@post = Post.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @post }
end
end
def create
@post = Post.new(params[:post])
#something else
end
Here since when we are actually creating a new post we call the method create where Page.new(params[:page]) is used, method new should only be used to call the view new.html.erb. So why we still need an instance variable @post in new method here?
Upvotes: 1
Views: 150
Reputation: 17323
You don't need any instance variables in new
or any other action, but by default, Rails's scaffolding uses them. There are some minor benefits that come with using instance variables, and there's some convention around them, but frankly it's sloppy code and should not be the default. In a proper MVC framework, the controller's instance variables wouldn't even be visible to the view object.
I prefer to be explicit, use local variables, and pass them to the view as locals:
def new
post = Post.new
respond_to do |format|
format.html { render locals: { post: post } }
format.json { render json: post }
end
end
This is more explicit, and makes your intent clear. The view becomes more flexible with locals, since you don't have to worry about setting instance variables before rendering a partial from inside another view. It properly encapsulates the data and doesn't expose your post
outside the action.
If you're trying to quickly prototype/spike something, you might save a few characters by using instance variables, but it's not clean code.
Upvotes: 2
Reputation: 7181
If you did not create a new instance variable then you wouldn't have a model to hold the data in which the model is supposed to be managing - not to mention you would be adding a lot more boiler plate for your forms instead of using the form helpers that take a model. Without using the model you're not using the MVC framework fully as intended.
Now that all being said, it's by no means required to do anything it's just following the MVC structure that Rails is built on top of. No pattern is required, there are always other solutions, it's just that the accepted method of performing this action involves a model - albeit and empty one.
Finally, I don't know when or why you'd want to respond with a new
route with JSON
since the new
route is generally used for displaying a form to create an object while the create
function is the one used to actually create a new instance of the model.
Upvotes: 0