Jonathan.
Jonathan.

Reputation: 55534

Views, Partials and Layouts in Ruby on Rails

A RESTful API means you can go to /posts and get a list of all posts, and go to /posts/:id to get a specific post. So I have a view called index for /posts and a view show for /posts/:id.

Seeing as the /posts is a list of posts, I'd like to just use the show view inside the index view to same me having the same HTML twice. But the show view is not a Partial view because it has it's own controller so how can I include it in index?

Also to add to this confusion, I don't understand why there are Views and Layouts? What situation would you need to use a Layout and not a View?

Upvotes: 0

Views: 73

Answers (2)

user3148371
user3148371

Reputation:

Layout is nothing but wrapper to your view content. It is also used to maintain same look and feel across the website. One of the purpose of Layout is to reduce redundancy i.e. DRY.

If you want to use show view code in index view, you need to modify your show view, move all your code of show view to a partial and call that partial in show by passing your resource as local. And you can use the same partial in index.

Upvotes: 1

Peter Alfvin
Peter Alfvin

Reputation: 29379

You can create a partial to display an individual post and invoke that partial from both your show and index controller methods.

Layouts are view elements intended to be shared across other "primary" view elements.

Upvotes: 1

Related Questions