第一部分:如何鏈接到與用戶關聯的帖子(導軌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'的關聯? –