0

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?

1
  • Feel free to ignore my edit, @apneadiving got to it before I did. Do you want to show apartments that belong to the region being viewed? Commented Aug 5, 2011 at 21:20

2 Answers 2

2

It would simply be:

@appartments = @region.appartments
Sign up to request clarification or add additional context in comments.

Comments

1

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.

7 Comments

@apneadiving Thanks for the edit, I went with my intuition and wrote apartments.
I think you created the partial with name appartment, it should be appartments. I hope it works.
partial created: <% @country.region.appartments.each do |appartment| %> <p> <%= link_to appartment.item.name %></td> </p> <% end %> but i got the message "undefined method `region' for #<Country:0x200272c>" What i am doing wrong?
Your Country model has_many countries, not one country. Hence, you need to iterate through the array of regions. This is what you need to do: <%= @country.regions.each do |region| %> <%= region.appartments.each do |apt| %> <%= link_to apt.item.name %> <% end %> <% end %>. Did that appartments partial not work? It should work. Did you change the partial name from _apartment.html.erb to _apartments.html.erb ?
It is working now.thanks!.....appartments.each do |appartment| <%= link_to appartment.item_name, country_region_appartment_url(@country, @region, appartment)...but the record is printed 2 times! is my each loop not correct?
|

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.