第一部分:如何链接到与用户关联的帖子(导轨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
的方法。谢谢您的帮助。
你是否设置了与'belongs_to'和'has_many'的关联? –