2016-04-16 28 views
0

我试图确保我的Rails应用程序安全地建立关联,我不知道我应该如何处理这种情况,我有通过另一个模型本质上“拥有”的模型。安全地建设模型协会

一个例子是我是一个拥有十几岁女儿的父亲。他们拥有一些苹果产品。产品在技术上属于他们,但我付出了一切 - 我拥有它。

此外,我不希望陌生人只给女儿新的苹果产品。

该代码,这看起来像:

class Father 
    has_many :teenage_daughters 

    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
end 

class TeenageDaughter 
    belongs_to :father 

    accepts_nested_attributes_for :apple_products, 
           reject_if: :all_blank, 
           allow_destroy: true # oh yeah 
end 

class AppleProduct 
    belongs_to :teenage_daughter 
    # Should i be doing something like this? 
    # belongs_to :father 
end 

我的问题是:

我应该BACK加入belongs_to关系到父亲的AppleProduct内,不知何故,每当我创建AppleProduct的I设置current_user

我担心出错,并以某种方式允许制作的请求,这将允许人们关联/取消关联行与不属于他们的用户帐户。

回答

2

让我引用的东西,你说:

我为它付出一切 - 我拥有它

这意味着该AppleProduct模型表示,父亲拥有资产,而你正在让某人(在这种情况下是孩子们)使用它。这是一个在我看来,更贴近现实生活的模型的方式:通过这样做

class Father 
    has_many :apple_products 
    has_many :teenage_daughters 
end 

class TeenageDaughter 
    belongs_to :father 
end 

class AppleProduct 
    belongs_to :owner, class_name: 'Father' 
    belongs_to :user, class_name: 'TeenageDaughter' 
end 

你的谁是owner以及这些产品的user明确表示。

此外,与您的问题无关,但考虑将名称从TeenageDaughter更改为Child