2012-04-01 61 views
1

我正在開發一個實踐的博客網站。我的問題是我無法將數據從一個對象調用到另一個相關對象。相關對象查詢軌跡3

這裏是我的模型關聯:

1 class Post < ActiveRecord::Base 
2 belongs_to :user 
3 end 

1 class User < ActiveRecord::Base 
2 has_many :posts 
3 end 

在控制檯:

user = User.find(1) 
user.posts // Everything works! It shows me a list of posts related to the user. 
user.post(1) //This doesn't work! Is it wrong? 

我在rubyonrails.org一直在尋找在活動記錄查詢界面引導,但仍無法找到任何東西參照這個。也許我錯過了什麼?

感謝

回答

1

這樣來做:

user.posts[0] #=> returns the user's first post 
+1

user.posts.first也是一種另類的方式來喬爾的回答。 – John 2012-04-01 04:26:39

+0

嘿!這工作!如果我想做user.create_posts,那也可以嗎?我在哪裏可以獲得更多信息? – cj3kim 2012-04-01 04:39:19

+0

另外,有沒有像'user.find_posts(x)',我可以使用,而不是users.posts [x]? – cj3kim 2012-04-01 05:01:33