7

I am following the Agile Web Development with Rails 4 book and I'm a bit confused on a part about rendering. The simple version of the question is... within the application.html.erb file there it says

render @cart

This is confusing because I thought that there needed to be a controller associated with that view in order to know which partial and @cart variable to use. Is it simply by naming convention that this line looks for a partial like _cart.html.erb? And in that case does it not actually know what @cart is until it renders that partial?

Some clarification would be lovely. Thanks!

1

1 Answer 1

10

This is a shorthand syntax. From the docs:

Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the :object option:

<%= render partial: "customer", object: @new_customer %>

Within the customer partial, the customer variable will refer to @new_customer from the parent view.

If you have an instance of a model to render into a partial, you can use a shorthand syntax:

<%= render @customer %>

Assuming that the @customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it and will pass the local variable customer into the partial which will refer to the @customer instance variable in the parent view.

Sign up to request clarification or add additional context in comments.

3 Comments

so if there is a :customer in the model, you can user render @customer and it doesn't pass any information and just looks for a partial named _customer?
it looks for the partial named _customer and also passes the instance variable named @customer which is defined from the parent view. In the first example in my answer, they are showing how to pass in a different instance variable, @new_customer, but if you have an instance variable with the same name, you can use the shorthand.
I think application.html.erb is the parent view. With render @cart in the application.html.erb, the variable @cart should change depending on what view is being accessed. So for the index action, @cart would be whatever is defined in the index controller. I'm sort of guessing here, though :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.