Ruby on rails 我如何授权给范围?轨道
我有:Ruby on rails 我如何授权给范围?轨道,ruby-on-rails,ruby-on-rails-4,scope,delegates,Ruby On Rails,Ruby On Rails 4,Scope,Delegates,我有: class UserItem < ActiveRecord::Base belongs_to :user belongs_to :item scope :equipped, -> { where(equipped: true) } end class Item < ActiveRecord::Base has_many :user_items has_many :users, through: :user_items scope :
class UserItem < ActiveRecord::Base
belongs_to :user
belongs_to :item
scope :equipped, -> { where(equipped: true) }
end
class Item < ActiveRecord::Base
has_many :user_items
has_many :users, through: :user_items
scope :armor, -> { where(type: 'Armor') }
delegate :equipped, to: :user_items
end
编辑:
如果我尝试
User.first.items.confided=>的未定义方法“confided”
User.first.items.armor.confided=>未定义的方法“装备”
如何委托给作用域?你不能轻易地委托给作用域,你也不想,因为它会从目标类UserItem而不是子类返回对象 相反,您可以非常简单地合并作用域:
class UserItem < ActiveRecord::Base
scope :equipped, -> { where(equipped: true) }
end
class Item < ActiveRecord::Base
scope :equipped, -> {joins(:user_items).merge(UserItem.equipped)}
end
=> Item.equipped
=> collection of items for which they have a user_item association that is equipped
编辑:有关此功能的一些文档
再次编辑:
如果确实希望从对Item调用的方法返回UserItems集合,则可以执行以下操作:
class Item
class << self
delegate :equipped, to: :UserItem
end
...
但这将返回集合中的UserItems,而不是Items。这就引出了一个问题:为什么要授权?
如果您想要一个项目集合,并且希望通过一个用户项目集合来限制这些项目,那么使用merge 您好,Matrix,我已经更新了我的答案,解释了为什么您可能不想实际执行您正在尝试执行的操作,以及您需要使用父作用域检索子项的方法。我一定是误解了这个问题,因为从您提出的问题中,我确信合并是解决方案。祝你好运如果我想在项目中使用范围,我将使用:范围:装备,->{where inventory\u items:{affeed:true}}},但这不是我的问题^^^我不需要downvote@Matrix我的示例中的范围在项目模型中,它加入了用户项目模型,并使用那里配备的范围来限制配备的用户项目返回的项目。除非我完全误解了你的问题,否则这就是你想要的?基本上,这会选择项。*from items加入user_items,其中user_items.confided=true。您想返回UserItem对象的集合吗?不,您已经理解了这个问题,但在Item模型中,我可以添加:scope:assembled,->{where user_items:{assembled:true}}}按用户替换库存,这在我的上一个com中是个错误,工作正常。但我的问题是:如何在UserItem中使用scope来不重新定义Item类中的作用域?您可以使用merge来使用关联模型的作用域,而无需在子类中重新定义它们。您不能对作用域使用委托。@Matrix好的,我肯定这不是您想要的,或者是个坏主意,但我添加了一个示例,可以直接将所配备的方法传递给UserItem类。。。以及我认为这是错误的原因。