2012-08-17 67 views
-3
@posts = Post.all 

Post.all將當前存在於數據庫中的所有帖子作爲我們存儲在名爲@posts的實例變量中的Post記錄數組返回。我只想獲取用戶的特定數據。我該如何做?我如何插入並從軌道中獲取數據從數據庫?

+0

你真的需要解釋你的問題多一點。你有用戶模型嗎?這個用戶模型與Post模型有關係嗎?讓我看看代碼! – 2012-08-17 10:50:05

+0

是的,我有用戶模型,但它與帖子模型沒有關係。 – usr 2012-08-17 10:51:37

+0

如何建立兩個模型之間的關係 – usr 2012-08-17 10:54:50

回答

0

首先,你需要生成一個遷移。

rails g migration add_user_id_to_posts user_id:integer 

然後,運行rake db:migrate,讓您的posts數據庫表中有一個user_id列。

現在,您需要修改user.rbpost.rb模型,以反映該協會

# app/models/post.rb 
class Post < ActiveRecord::Base 
    ... 
    belongs_to :user 
    ... 
end 

# app/models/user.rb 
class User < ActiveRecord::Base 
    ... 
    has_many :posts 
    ... 
end 

在此之後,重新啓動您的軌道服務器。現在,您將可以訪問特定於此類用戶的帖子

# Let fetch User with ID 1 
user = User.find(1) 
# Now, we can fetch posts related to this user like 
@posts = user.posts 
# Or like this 
@posts = Post.where(:user_id => 1).all 

我希望這很容易遵循。瞭解有關Rails ActiveRecord Associations

+0

謝謝你這麼多。 – usr 2012-08-17 11:01:48

0

@posts = specific_user.posts.all

,你需要確保樁模型belongs_to的用戶模型和用戶模型的has_many帖子

+0

如何建立兩種模型之間的關係 – usr 2012-08-17 10:55:35

+0

不要粗魯,但這是關於Rails教程的第一部分。請先做他們,否則你會問更多的問題,而不是*瞭解*你在做什麼...... – 2012-08-17 10:59:23

0

如果要過濾結果,可以使用'where'方法。

例如,過濾通過用戶名帖子,嘗試:

@posts = Posts.where(:username => "jondoe") 

您也可以使用:條件符號上的「發現」的方法,通過SQL在這種情況下。

例如,通過用戶名和公共標誌進行過濾,請嘗試:

@posts = Posts.all(:conditions => "username='johndoe' AND public=1") 
相關問題