2013-08-16 33 views
2

第一部分:如何链接到与用户关联的帖子(导轨4)?

我有一个索引页面,列出了我的应用程序中的所有帖子。我希望能够点击链接标题并将其重定向到帖子展示页面。这是我的索引页面。

<% provide(:title, "All Posts") %> 
<% @posts.each do |post| %> 
    <div> 
     <h2><%= link_to post.title.titleize, post %> by <%= post.author.name.titleize %></h2> 
     <div><%= post.body %></div> 
    </div> 
<% end %> 

当我尝试去我index页我得到

undefined method `post_path' for #<#<Class:0x007fc6df41ff98>:0x007fc6df436e78> 

我敢肯定,在我的link_to的post其原因,但我不知道我会放在那里让它去到正确的地方。当我运行rake routes它表明帖子#show动作是

user_post GET /users/:user_id/posts/:id(.:format)  posts#show 

,所以我试着用user_post_path(post)更换post但后来我得到

No route matches {:action=>"show", :controller=>"posts", :user_id=>#<Post id: 4, title: "werwef", body: "erfwerfwerf", user_id: 3, created_at: "2013-08-16 20:05:43", updated_at: "2013-08-16 20:05:43">, :id=>nil, :format=>nil} missing required keys: [:id] 

什么应该把它改成?

第二部分:

<%= post.author.name.titleize %>打印出贴帖子的用户名,并即时得到它从我在我的岗位模型

def author 
    User.find(self.user_id) 
end 

定义的方法是这样的最好的方法来做到这一点?在我做出这个方法之前,我尝试了post.user.name,但那不起作用,只是告诉我没有定义user的方法。谢谢您的帮助。

+0

你是否设置了与'belongs_to'和'has_many'的关联? –

回答

4

第一部分

由于这些嵌套的路径,你有没有考虑通过用户以及邮政?最终网址需要一个user_id以及一个post_id,所以你可能需要调用如下:

<%= link_to user_post_path(post.user, post) %> 

的文档是在这里:Rails Guide on Nested Resources

this SO question提取。

第二部分

您可能会错过协会呼吁:

Post.rb

belongs_to :user

User.rb

has_many :posts

然后你可以使用post.user

+0

虽然含义可能会说清楚,但我只是想明确指出'/ users /:user_id/posts /:id'有2个参数,'user_id'和'id'。 'user_post_path'中的第一个参数将对应于'user_id',第二个参数对应'id'。 Rails不会推断这一点。就我个人而言,当我遇到这些问题时,我考虑是否存在一种更优雅的方法,我不需要嵌套整个路线。例如,也许你可以做'resources:posts,:only => [:edit,:update]'或者其他类似的东西。如果你不需要用户ID,或者可以尝试一种不同的方式 – David

+0

@david - 我需要用户id为:new和:create too? – oobie11

+0

@ oobie11在你的路线中有两个或更多参数的地方,那么你将需要通过许多参数。但是,你永远不应该有两个以上的参数。如果你有两个以上,重新考虑你的路由设计是一个好主意。如果你的:new和:create在路由中也有:user_id和:id,那么你需要user_id。 – David