2014-02-23 88 views
0

嘿所以我有一個基本的架構,我正在實施。以下是基本款Rails中的多態多態模型

User - Public Free User of App 
Organization - Subscribes to app, has employees 
Employee - Belongs to an organization 

這裏是我的多態性部分

Post - Can be made by employees or users 
Image - Multiple can be attached to either posts or comments 
Comment - Can be added to images or posts by either employees or users 

用戶和員工是不同的。

多態圖像完成。我遇到麻煩的地方是評論部分。我如何進行設置,以便評論可以與圖片或帖子相關聯,並且可以由員工或用戶發佈。這是我到目前爲止。

class Comment < ActiveRecord::Base 
    belongs_to :commentable, :polymorphic => true 
end 

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

class Image < ActiveRecord::Base 
    has_many :comments, :as => :commentable 
end 

這將設置它,以便評論可以屬於職務或圖像,我該如何設置它,以便員工/用戶可以有很多的意見,因爲他們加入他們嗎?或者我應該把它分解成EmployeeComments和UserComments。

看來我需要另一張表來承載多態所有權關聯。

回答

1

您只需要將另一個多態性belongs_to關聯添加到代表評論作者的Comment模型。

class Comment < ActiveRecord::Base 
    belongs_to :commentable, :polymorphic => true 
    belongs_to :authorable, :polymorphic => true 
end 

class User < ActiveRecord::Base 
    has_many :comments, :as => :authorable 
end 

class Employee < ActiveRecord::Base 
    has_many :comments, :as => :authorable 
end