我对不显示正确 url 的嵌套路由有疑问。
我使用下面的代码,但它呈现如下:
.../users/[:user_id]/microposts/[:user_id]
代替:
.../users/[:user_id]/microposts/[:micropost_id]
对于用户展示页面中显示的每个微博。
协会
has_many :microposts #user model
belongs_to :users #micropost model
路线
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
用户/show.html.erb
<%= render @microposts %>
我看不出我错在哪里。非常感谢您的帮助!
编辑
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
路线:
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"}