如何使用范围块重写has_many?

时间:2014-02-18 11:05:26

标签: ruby-on-rails activerecord

宣言:

  has_many :read_access_mappings, 
           :primary_key => "username", 
           :foreign_key => "username", 
           :class_name => 'Mapping',
           :conditions => {"mappings.read_access" => true}

收到警告:

  

弃用警告:User.has_many中的以下选项   :read_access_mappings声明已弃用:: condition。请   改为使用范围块。

如何用新语法重写它?

2 个答案:

答案 0 :(得分:0)

我认为最好的解决方案:

class Cls
 has_many :readable_mappings,
          -> { readable },
          primary_key: 'username',
          foreign_key: 'username',
          class_name: 'Mapping'
end

class Mapping
  scope :readable, where(read_access: true)
end

cls_instance.readable_mappings

答案 1 :(得分:0)

也许你可以试试这个:

has_many :read_access_mappings, -> { where read_access: true },class_name: 'Mapping',
           primary_key => "username", 
           foreign_key => "username" 

Source