为什么这个嵌套资源link_to正在寻找“destroy”而不是“show”?

时间:2010-10-28 19:30:55

标签: ruby-on-rails-3

我只是想让链接指向“user / 1 / post / 1”。我尝试使用带有和不带:方法键的link_to并获得相同的结果。

ActionController::RoutingError in Posts#index

Showing /home/test/rails_apps/test_app/app/views/posts/index.html.erb where line #22 raised:

No route matches {:action=>"destroy", :controller=>"posts", :user_id=>#<Post id: 1, content: "wtf", user_id: 1, created_at: "2010-10-27 20:46:46", updated_at: "2010-10-27 20:46:46">}

Extracted source (around line #22):

22:     <td><%= link_to 'Show', user_post_path(p), :method => :get %></td>

2 个答案:

答案 0 :(得分:1)

注意“:method”参数。它指定HTTP方法,而不是操作。

答案 1 :(得分:0)

您正在使用user_post_path(p),我猜p => Post Object

但是这条路线也需要一个用户对象,因此该资源将评估为a post of a user

查看this

它说

In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes:

resources :magazines do
  resources :ads
end

When using magazine_ad_path, you can pass in instances of Magazine and Ad instead of the numeric IDs.
<%= link_to "Ad details", magazine_ad_path(@magazine, @ad) %>

You can also use url_for with a set of objects, and Rails will automatically determine which route you want:
<%= link_to "Ad details", url_for([@magazine, @ad]) %>

希望这有帮助。