Ruby on rails 如何在RubyonRails中链接到users/id/microscops?
我需要创建一个指向Ruby on rails 如何在RubyonRails中链接到users/id/microscops?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我需要创建一个指向users/id/microposts的链接,其中id是用户id。我想知道如何使用link\u实现这一点 我目前使用的HTML代码是: <strong><a href="/users/<%= @user.id %>/microposts">Microposts</a></strong> <%= user.microposts.count %> 这使得: <a href="/users/1/mic
users/id/microposts
的链接,其中id
是用户id。我想知道如何使用link\u实现这一点
我目前使用的HTML代码是:
<strong><a href="/users/<%= @user.id %>/microposts">Microposts</a></strong> <%= user.microposts.count %>
这使得:
<a href="/users/1/microposts">Microposts</a>
假设您的路由设置正确,这将是MicroPost的嵌套路由,在rails 3中是这样的
resources :users do
resources :microposts
end
那么在你看来,通过链接你可以
<%= link_to "Microposts", user_microposts_path(user) %>
这可能是当前用户,@user。。。无论您想要MicroPost的用户对象是什么,它都可能来自
@users.each do |user|
<%= link_to "Microposts", user_microposts_path(user) %>
end
@users.each do| user|
结束
或
编辑:在用户对象中添加了我忘记传入的内容和一些示例。在routes.rb中,您应该有如下内容:
match '/users/:id/microposts' => 'microposts#index_by_user', :as => :microposts_by_user
<%= link_to "Microposts", microposts_by_user_path( @user) %>
鉴于此,您可以这样做:
match '/users/:id/microposts' => 'microposts#index_by_user', :as => :microposts_by_user
<%= link_to "Microposts", microposts_by_user_path( @user) %>
在这种情况下,我认为您需要将用户
对象传递到User\u microsofsts\u路径
。我尝试了您的解决方案,但出现了以下错误ActiveRecord::RecordNotFound in microsofstsController#索引-找不到没有ID的用户
。我想我需要使用@nitecoder的解决方案?你能告诉我怎么做吗?非常感谢!这起作用了。我使用了index
操作,而不是用户的index\u
。这是不是不太地道?