0

正しい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

user / 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"}
4

1 に答える 1

2

@micropostも渡す必要があります:

<%= link_to "show this micropost", user_micropost_url(@user, @micropost) %> #link for every microposts displayed

次のように短縮することもできます。

<%= link_to "show this micropost", [@user, @micropost] %> #link for every microposts displayed
于 2011-03-23T09:15:19.340 に答える