2016-09-25 166 views
0

我有一個Users模型與has_many :comments 每個評論記錄current_usercommenter列。如何從子表中獲取信息

如何在我的視圖中調用@ commenter.username並顯示評論者的用戶名?

目前在comments_controller中使用:@commenter = User.find("2")會拉出正確的信息。我想用線沿線的東西:@commenter = User.find_by_id(:commenter)

+0

你能否提供一些實際的代碼(例如模型代碼)?真的很難理解你的模型關係看起來像讀這個。 –

+0

你的數據庫模式也會有所幫助。我不明白你爲什麼使用'commenter'作爲你的列名,標準格式對'belongs_to'關係是'user_id'。 –

+0

@ChrisSalzberg對不起,我正在使用user_id將評論與用戶頁面相匹配,評論者僅針對發佈評論的用戶。此外,除了belongs_to/has_many之外,還沒有關於評論的模型代碼 – aidiah

回答

1

從評論,這聽起來像你有這樣的Comment型號:

class Comment < ActiveRecord::Base 
    belongs_to :user 
end 

註釋模型代表了用戶的頁面,其中上評論用戶模型定義爲:

class User < ActiveRecord::Base 
    has_many :comments 
end 

還有在comments表來存儲誰張貼該評論的用戶(在OTH一個commenter列呃用戶的頁面)。

首先,我會建議使用commenter_id這個列而不是commenter,因爲這是存儲任何類型的ID的慣例。

假設你對commentscommenter_id列,那麼您需要定義一個關係如下:

class Comment < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :commenter, class_name: "User", foreign_key: :commenter_id 
end 

commenter關係定義誰該評論的用戶,而不是用戶的評論是在的頁面上。

對於這種關係的另一面,更新您的User型號:

class User < ActiveRecord::Base 
    has_many :comments 
    has_many :page_comments, class_name: "Comment", foreign_key: :commenter_id 
end 

這裏,page_comments定義該用戶已發佈了對其他用戶的網頁的評論。

然後,如果你有一個@comment,你可以簡單地得到了評論者的名字:

@comment.commenter.name 

只要您設置您的列名和模型正確,處理獲取信息這應該是很簡單的。

+0

這工作,但沒有@符號,只是'comment.commenter。用戶名' – aidiah

+0

很高興聽到! –