【问题标题】:Private association in rails铁路私人协会
【发布时间】:2012-08-21 08:10:39
【问题描述】:

我有两个 ActiveRecord 模型:

class Foo < ActiveRecord::Base
  has_many :bars,:dependent=>:destroy
end

class Bar < ActiveRecord::Base
  belongs_to :foo
end

我的设计规定Bar 需要与Foo 相关联,但Foo 仅与Bar 相关联以用于数据库依赖——以确保当Foo 的实例被删除时,所有Bar 的关联实例也将被删除。除此之外,使用Foo 的代码不应该知道Bar,我不希望可以从Foo 对象访问关联方法。

我尝试在Foo 中的has_many 声明之前声明private,但它不起作用(我猜它只适用于直接用def 声明的方法...)。

有什么方法可以使关联私有化,或者实现数据库依赖而不在Foo 中创建Bar 关联?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations


    【解决方案1】:

    您必须在调用has_many 之后将private 声明,因为直到那时才定义关联的方法:

    class Foo < ActiveRecord::Base
      has_many :bars, :dependent => :destroy
      private :bars, :bars=
    end
    
    Foo.first.bars
    #=> #<NoMethodError: private method `registrations' called for #<Foo:0x007fc767adca88>>
    

    【讨论】:

    • 谢谢!我还将 bar_idsbar_ids= 设为私有 - 不如将 barsbars= 设为私有重要,但应注意解决方案的完整性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多