2011-10-10 55 views
0

我真的开始哭了;)试图在模型索引视图中建立链接。初学者:简单link_to /路由

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

我想在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索引操作中指定@user吗?我真的很感谢这里的长时间回复。

TNK SOOOO多的耐心初学者;)

回答

1

你可能有这样的在你的路线 -

resources :posts do 
    resources :users 
end 

耙路线会产生下面的映射 -

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]) %> 
+0

Jayendra帕蒂尔<3 –

+0

你可能要接受的答案,如果解决方案适用于你。会帮助人们进一步帮助你。 – Jayendra