Remco
Remco

Reputation: 683

nested resources in rails 3

My routes file is:

resources :countries do
  resources :regions do 
    resources :appartments
  end
end

models:

Country: has_many :regions

Region: belongs_to :country, has_many :appartments

Appartment: belongs_to: region

Region_controller:

def index
  @country = Country.find(params[:country_id])
  @regions = @country.regions
end


def show
  @country = Country.find(params[:country_id])
  @region = @country.regions.find(params[:id])
end  

Question:

I want to show appartments on the region page. What's the best practice in my region controller?

Upvotes: 0

Views: 137

Answers (2)

rookieRailer
rookieRailer

Reputation: 2341

If all you want to do is to show apartments within the regions show page, do the following:

  1. create an instance variable in the regions show action as:

    @appartments = @regions.appartments

  2. create a partial _appartments.html.erb in the views/regions folder

  3. Somewhere within the regions/show.html.erb page, place this:

    <%= render @appartments %>

This should do the trick.

Upvotes: 1

apneadiving
apneadiving

Reputation: 115511

It would simply be:

@appartments = @region.appartments

Upvotes: 2

Related Questions