When you say render(@cart)
, what's really happening behind the scenes is Rails is making a lot of assumptions for you based on the conventions of how Rails generally works.
Let's start off with the @cart
variable. This is an instance variable, which is a variable that's accessible to anything inside your controller. Views have a special relationship with controllers, so instance variables defined within a controller method are available within the view.
You could use @cart
within your partial, and everything would work fine in this case. But it's generally a bad idea - you want partials to be reusable in different spots, and assuming that an instance variable exists introduces coupling between your controller and the partial.
The solution that Rails provides is the ability to pass local variables to a partial. Remember how I said that render(@cart)
is a shortcut? What's really happening behind the scenes is this:
render partial: 'carts/cart', locals: { cart: @cart }
Because you're following Rails conventions, Rails can make the following assumptions:
- The partial for a
Cart
is located inapp/views/carts/_cart.html.erb
- That partial is going to use a local variable named
cart
, which is passed to the method.
So as a result, the following:
render @cart
has the same effect as the more verbose line above.