【问题标题】:Securely building model associations安全地建立模型关联
【发布时间】:2016-04-16 21:25:03
【问题描述】:

我正在努力确保我的 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

我的问题是:

我是否应该在AppleProduct 内部添加belongs_to 关系BACK 到父亲,并且每当我创建AppleProducts 时我设置current_user

我担心会犯错误并以某种方式允许精心制作的请求,这将允许人们将行与不属于他们的用户帐户关联/解除关联。

【问题讨论】:

    标签: ruby-on-rails ruby security associations belongs-to


    【解决方案1】:

    让我引用你说的话:

    我付出了一切——我拥有它

    这意味着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
    

    通过这样做,您可以明确表示谁是这些产品的owneruser

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多