Rails 3 / nested routes: Problem to redirect to the correct url for a collection of microposts in a user show page
I have a problem with nested routes which don't display correct url.
I use the be开发者_如何学JAVAlow code, but it renders something like:
.../users/[:user_id]/microposts/[:user_id]
instead of:
.../users/[:user_id]/microposts/[:micropost_id]
for every microposts displayed in the user show pages.
Associations
has_many :microposts #user model
belongs_to :users #micropost model
routes
resources :microposts, :only => [:create, :destroy]
resources :users, :only => [:show] do
resources :microposts, :only => [:show]
end
Microposts_controller
def show
@user = User.find(params[:user_id])
@micropost = @user.microposts.find(params[:id])
end
microposts/_micropost.html.erb
<%= link_to "show this micropost" user_micropost_url(@user) %> #link for every microposts displayed in the user show pages
user/show.html.erb
<%= render @microposts %>
I can't see where I am wrong. Thank a lot for your help!
EDIT
if I use [@user, @micropost ] the displayed url is .../users/[:user_id]
if I use user_micropost_url(@user, @micropost) it renders an error:
No route matches {:action=>"show", :controller=>"microposts", :user_id=>#<User id: 1
Routes:
user_micropost GET /users/:user_id/microposts/:id(.:format) {:action=>"show", :controller=>"microposts"}
microposts POST /microposts(.:format) {:action=>"create", :controller=>"microposts"}
micropost DELETE /microposts/:id(.:format) {:action=>"destroy", :controller=>"microposts"}
user GET /users/:id(.:format) {:action=>"show", :controller=>"users"}
You need to pass in @micropost as well:
<%= link_to "show this micropost", user_micropost_url(@user, @micropost) %> #link for every microposts displayed
You could also shorten it to:
<%= link_to "show this micropost", [@user, @micropost] %> #link for every microposts displayed
精彩评论