开发者

BEGINNER: simple link_to / routing

I'm really starting to cry here ;) Trying to make a link in a Models index view.

I have 2 simple Models: Users and Posts. There both generated with scaffolding and have working joins. A user has_many :posts and a post belongs_to :user.

What I'm trying to do in the views/post/index.html.er file is a list of the Post title and the user who it belongs to. It works well (also learning html5):

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

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

<% end 开发者_开发知识库%>

Well, it works but the "users_path" is not what I want. I want to link to the specific User which the post belongs_to. I'm sorry to say that I don't get much help from http://guides.rubyonrails.org/routing.html.

How should I do this? Do I have to specify a @user in the posts_controller index-action? I reallt appreciate long and detaild answears here.

Tnk soooo much for patience with a beginner ;)


you probably have this in your routes -

resources :posts do
  resources :users
end

rake routes would generate the following mapping -

    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"}

The above explains the url you can use and what objects need to be passed.
For linking the user of the post -

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

OR

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜