2013-08-23 69 views
0

如何在Rails中實現這種結構?如何添加關聯到模塊?

User 
has_one :health 
Health 
belongs_to :user 
has_many :weights 
has_many :diseases 

Health::Weight 
belongs_to :health 
Health::Diseases 
belongs_to :health 

users 
health_id:integer 
healths 
id:integer 
health_weights 
current:integer 
health_id:integer 
health_diseases 
name:text 
health_id:integer 

當我產生r g model Health::Weight current:integerHealth是沒有ActiveRecord的模塊:

module Health 
    def self.table_name_prefix 
    'health_' 
    end 
end 

我這個好辦法?

+0

所以,這裏有什麼問題嗎? –

+0

我更新了問題。 – tomekfranek

回答

1

據我瞭解你想要達到的是這樣的:

  1. 給定用戶的健康狀況可能對健康有很多特徵(體重,疾病等)。

  2. 你想要把相應的健康特性模型模塊中明確他們從你的應用程序的其他部分分開


這是一個很好的情況下,實際上是用「健康」模塊正如您爲Health :: Weight and Health :: Diseases所做的那樣。

但是,您不應該使用稱爲Health的模型作爲您的模型,將用戶鏈接到其健康特徵。

這首先導致混淆語義,但它也不會在代碼中工作:健康不能同時是一個ActiveRecord :: Base子類(或其他'ORM類')和封裝其他表的模塊像體重和疾病。


=>與明確指出,這是一個用戶及其對健康的特點(重量,疾病等)之間的聯繫更清晰的模型名稱替換您的健康模式。例如UserHealthProfile。

最終結構將是:

class User 
     has_one :user_health_profile 
    end 

    class UserHealthProfile 
     belongs_to :user 
     has_one :weight 
     has_many :diseases 
    end 

    module Health 
     def self.table_name_prefix 
     'health_' 
     end 
    end  

    class Health::Weight 
     belongs_to :user_health_profile 
    end 

    class Health::Disease 
     belongs_to :user_health_profile 
    end 

你也可以把你的UserHealthProfile模型衛生模塊內部,像這樣:

class Health::UserHealthProfile 
    end 

注意:當封裝模式爲模塊,在定義關聯時可能需要添加class_name參數,但這取決於您的a實際模塊結構。

例子:

# let's say UserHealthProfile doesn't belong to the Health module 
    class UserHealthProfile 
     belongs_to :user 
     has_one :weight, class_name: Health::Weight 
     has_many :diseases, class_name: Health::Disease 
    end  
0

如果你真的想生成模塊內您的模型/控制器,改變這種:

rails g model Health::Weight current:integer 

rails g model health/weight current:integer 

不過,我個人不會理會,除非你真的有這麼多模型,你不能跟蹤他們所有。

0

不擅長。

建模是試圖抽象真實世界的對象。除User外,您的模型都不是真實世界。

用戶如何擁有一個健康?健康怎麼會有很多重量?健康有多少疾病?在現實世界中它們都不是可以理解的。

我的建議不是讓模型像樹一樣,而是從真正的問題開始解決。

例如,用戶可能有許多重量記錄。用戶可能有許多疾病。

+0

我想從用戶表中分離與健康相關的模型,並且可能不是完全健康模型,而是將這些模型與用戶模型相關的類似內容。這是因爲我必須遵守隱私法。 – tomekfranek

+0

@regedarek,我不能判斷不知道真正的問題領域。但你可以用簡單的模型名稱隱藏任何你想要的東西。 –