安全地建立模型关联
Securely building model associations
我正在努力确保我的 Rails 应用程序正在安全地建立关联,但我不确定我应该如何处理我的模型本质上是 "owned" 通过另一个模型的情况.
举个例子,我是一个有十几岁女儿的父亲。他们拥有一些苹果产品。这些产品在技术上属于他们,但我支付了所有费用——我拥有它。
此外,我不希望陌生人只是给我女儿新的苹果产品。
代码如下:
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
我的问题是:
我是否应该在 AppleProduct
中添加一个 belongs_to
返回到父亲的关系,并且每当我创建 AppleProduct
时我都会设置 current_user
?
我担心犯错并以某种方式允许精心设计的请求,这将允许人们使用不属于他们的用户帐户 associate/disassociate 行。
让我引用你说的话:
I paid for it all -- I own it
这意味着 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
。
我正在努力确保我的 Rails 应用程序正在安全地建立关联,但我不确定我应该如何处理我的模型本质上是 "owned" 通过另一个模型的情况.
举个例子,我是一个有十几岁女儿的父亲。他们拥有一些苹果产品。这些产品在技术上属于他们,但我支付了所有费用——我拥有它。
此外,我不希望陌生人只是给我女儿新的苹果产品。
代码如下:
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
我的问题是:
我是否应该在 AppleProduct
中添加一个 belongs_to
返回到父亲的关系,并且每当我创建 AppleProduct
时我都会设置 current_user
?
我担心犯错并以某种方式允许精心设计的请求,这将允许人们使用不属于他们的用户帐户 associate/disassociate 行。
让我引用你说的话:
I paid for it all -- I own it
这意味着 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
。