Tag: polymorphic association

ActiveRecord通过针对STI类的作用域构建错误类的实例

我希望能够通过其STI类型在一个以某类模型为目标的作用域上调用build方法,并让ActiveRecord构建一个正确类的实例。 class LineItem < ActiveRecord::Base scope :discount, where(type: 'DiscountLineItem') end class DiscountLineItem LineItem.discount.build # Expect an instance of DiscountLineItem here => # 在这里,我期待一个DiscountLineItem的实例,而不是LineItem一个实例。

RoR:has_one“或其他”? (或者,没有inheritance的多态性。)

嘿所有,我对我的项目有一些有趣的要求。 我需要一个has_one关系,它是一个类或另一个类,但没有inheritance。 如果它是唯一的方法,我可以逃脱inheritance,但是两个相关记录具有完全不同的数据并且根本不相关。 我需要弄清楚的是以下内容。 # 1. Foo never belongs to anything. # 2. Foo MUST have one assigned sub-record for validity. # 3. Foo can only have either Bar or Baz assigned. # 4. Bar and Baz have only ONE common property, and aren’t # related in either data or implementation. class Foo ‘assigned_to’, :readonly […]

Rails:构建涉及多态关联和STI的查询

我正在尝试找到关于照片的10条最新评论,因此我可以将它们集成到我的Rails 3.0.3应用程序的活动源中。 我有一个Photo模型,它inheritance了使用单表inheritance的Upload模型: class Upload < ActiveRecord::Base … end class Photo :commentable … end 可评论的多态关联在Comment模型中描述: class Comment true end 到目前为止一切都那么好吧? 当我尝试构建查询时出现问题。 经过一些试验和错误,我想出了这个代码,它位于Photo模型中: def self.latest_comments(count = 10) Comment.where(:commentable_type => “Upload”)\ .joins(“INNER JOIN uploads ON comments.commentable_id = uploads.id”)\ .where(“uploads.type” => “Photo”).order(“comments.created_at DESC”).limit(count) end 这段代码适用于我的SQLite开发机器,但是我必须做一些修改才能让它在使用PostgreSQL的生产服务器上运行。 上面的查询化身尚未在生产服务器上进行过测试,但我一直在寻找一种更简洁的结构化查询方式,因为上面的内容并不十分健壮,也不像“Railsy”。 我想要的是能够说的是 Comment.joins(:commentable => :photo) …但是这引发了一个exception,大概是因为Rails不知道如何进行连接: ActiveRecord :: EagerLoadPolymorphicError:无法急切加载多态关联:commentable 我在StackOverflow上发表了一篇文章 ,描述了一种查询多态关联的不同方式。 我能够根据这篇文章提出以下代码: Comment.find_all_by_commentable_type(“Upload”, […]

的ActiveRecord :: HasManyThroughAssociationPolymorphicSourceError

我需要一个玩家拥有许多结构和属于玩家的结构。 结构是一种多态关系。 class Player player_structures end class PlayerStructures < ActiveRecord::Base belongs_to :structure, polymorphic: true belongs_to :player end class StructureA :structure has_one :player, :through => :player_structure end class StructureB :structure has_one :player, :through => :player_structure end 但是如果我拉出Player.first并询问它的结构,它会给出: ActiveRecord::HasManyThroughAssociationPolymorphicSourceError: Cannot have a has_many :through association ‘Player#structures’ on the polymorphic object ‘Structure#structure’. 但它应该能够生成一个SQL查询,在其中找到所有带有id的player_structures,然后根据structure_id和structure_type获取结构。 为什么这会失败,我怎样才能有效地构建多态连接表? UPDATE 如果我按手动方式执行操作,则可以: player_structures.collect(&:structure) Rails,你不这样做吗?