2

I have 2 main components to my application, Users and Properties. The URL should be structured like: hostname.com/users/:user_id/properties/:property_id. I believe I've made a configuration error somewhere, because Rails never recognizes "property_path" or any of its variants, and I've had to hard code them in to get the redirects to work.

routes.rb

  resources :users do
    resources :properties
  end

users/show.html.erb - Notice I had to hard code the path, instead of simply linking to "i"

<% @user.properties.each do |i| %>
<li><%= link_to "#{i.address}", "/users/#{@user.id}/properties/#{i.id}" %></li>
<% end %>


How can I better define my routes so that I can link above to just "i", which would represent the "properties_path", and would auto redirect to that show page?

tomtom
  • 1,130
  • 2
  • 11
  • 35
  • 1
    See http://stackoverflow.com/questions/1548009/rails-link-to-routes-and-nested-resources for answer – atomAltera Jul 24 '14 at 14:04
  • thanks @atomAltera, and my mistake for missing that one. This seems to definitely be a duplicate question then – tomtom Jul 24 '14 at 14:09

1 Answers1

4

You don't have to hardcode it. You can do:

<% @user.properties.each do |property| %>
  <li><%= link_to property.address, [@user, property] %></li>
<% end %>

Yes, it's that simple. For more information, you can go to Rails guides.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
  • 1
    Nice, I wasn't aware you could link like that at all, but now it totally makes sense. With that structure, Rails will look for the 'property' path only if it's associated with @user. Thanks Marek, I'll accept the question in 7 minutes when it allows me – tomtom Jul 24 '14 at 14:08