2013-08-16 66 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