BEGINNER:简单的link_to / routing

时间:2011-10-10 17:50:30

标签: ruby-on-rails-3 html5

我真的开始哭了;)试图在模型索引视图中建立一个链接。

我有2个简单的模型:用户和帖子。这两个都是用脚手架生成的,并且有工作连接。用户has_many:帖子和帖子belongs_to:user。

我在views / post / index.html.er文件中尝试做的是Post标题及其所属用户的列表。它运作良好(也学习html5):

<% @posts.each do |post| %>

<p><%= link_to post.user.name, users_path %>: <b><%= post.title %></b></p>

<% end %>

嗯,它有效,但“users_path”不是我想要的。我想链接到帖子belongs_to的特定用户。我很遗憾地说http://guides.rubyonrails.org/routing.html我得不到多少帮助。

我该怎么做?我是否必须在posts_controller index-action中指定@user?我很欣赏这里长期和详细的回答。

Tnk soooo非常耐心和初学者一起;)

1 个答案:

答案 0 :(得分:1)

你可能在你的路线中有这个 -

resources :posts do
  resources :users
end

rake路由会生成以下映射 -

    post_users GET    /posts/:post_id/users(.:format)          {:action=>"index", :controller=>"users"}
               POST   /posts/:post_id/users(.:format)          {:action=>"create", :controller=>"users"}
 new_post_user GET    /posts/:post_id/users/new(.:format)      {:action=>"new", :controller=>"users"}
edit_post_user GET    /posts/:post_id/users/:id/edit(.:format) {:action=>"edit", :controller=>"users"}
     post_user GET    /posts/:post_id/users/:id(.:format)      {:action=>"show", :controller=>"users"}
               PUT    /posts/:post_id/users/:id(.:format)      {:action=>"update", :controller=>"users"}
               DELETE /posts/:post_id/users/:id(.:format)      {:action=>"destroy", :controller=>"users"}
         posts GET    /posts(.:format)                         {:action=>"index", :controller=>"posts"}
               POST   /posts(.:format)                         {:action=>"create", :controller=>"posts"}
      new_post GET    /posts/new(.:format)                     {:action=>"new", :controller=>"posts"}
     edit_post GET    /posts/:id/edit(.:format)                {:action=>"edit", :controller=>"posts"}
          post GET    /posts/:id(.:format)                     {:action=>"show", :controller=>"posts"}
               PUT    /posts/:id(.:format)                     {:action=>"update", :controller=>"posts"}
               DELETE /posts/:id(.:format)                     {:action=>"destroy", :controller=>"posts"}

以上说明了您可以使用的网址以及需要传递的对象 用于链接帖子的用户 -

<%= link_to "Post User details", post_user_path(post, post.user) %>

OR

<%= link_to "Post User details", url_for([post, post.user]) %>