2016-02-08 40 views
0

嗨我有一個評論對象,我使用多態關聯,因此它可以屬於許多其他對象。但我也希望他們屬於用戶。對象可以有2個父母在欄杆中嗎?

現在我可以打電話給comment.comment_owner,我得到了評論此評論的對象。

至於用戶,我在註釋對象中有一個user_id字段,我通過表單傳遞用戶標識。但是,當我嘗試通過comment.user獲取擁有者用戶時,我收到一條錯誤消息。現在我正在通過User.find(comment.user_id)獲取用戶。但是這看起來很糟糕。

有沒有辦法傳遞用戶ID。因此,我可以通過comment.user

我協會獲得用戶擁有自己的評論:

class Comment < ActiveRecord::Base 
    belongs_to :comment_owner, polymorphic: true 
end 

class User < ActiveRecord::Base 
    has_many :comments, as: :comment_owner 
end 

class Posts < ActiveRecord::Base 
    has_many :comments, as: :comment_owner 
end 
+0

提供您的協會,請 –

回答

1

爲什麼不

class Comment < ApplicationRecord 
    belongs_to :user 
end 
+1

這麼簡單,它是如此簡單。當我做多態關聯時,我忘記了它也可以以正常方式關聯。日Thnx。 – Kazik

0

首先,在我看來comment_owner是不是一個好名字是你這裏正在設計。評論所有者會建議所有權關係(而不是一個人或某人)。我想把它稱爲commentable,因爲這些對象正在被評論。

如果這個關係意味着是一個多態的,那麼你應該有commentable_typecommentable_id(或comment_owner_typecomment_owner_id如果你真的喜歡原始)polymorphic => true希望有這兩個字段(命名爲:relation_name_typerelation_name_id)。

如果你有一個評論對象,你可以通過調用comment.commentable(或者comment.comment_owner來防止你的命名)來評論用戶。

[編輯] 正如你所說,你想有兩個父母。如果我得到這個權利,你只是想有兩個關係 - 這意味着,如果你只是修改代碼以:

class Comment < ActiveRecord::Base 
    belongs_to :commentable, polymorphic: true 
    belongs_to :author, class_name: 'User' 
end 

class User < ActiveRecord::Base 
    has_many :comments, as: :commentable 
    has_many :notes, class_name: 'Comment' 
end 

class Post < ActiveRecord::Base 
    has_many :comments, as: :commentable 
end 

你將擁有多態性關係以及所有權。

+0

至於名稱,comment_owner是指評論此評論的對象(我有comment_owner_type和comment_owner_id字段)。這就是爲什麼當我打電話給comment.comment_owner時,我得到了評論對象,並且我還想要一個選項來調用comment.user來獲取評論的作者。 – Kazik

相關問題