ruby-on-rails - rails has_one 一个 has_many 关联

标签 ruby-on-rails activerecord model polymorphic-associations

我有一个产品,一个产品可以有很多图片。这是通过关联表。但是,我希望产品具有一个主要图像。

我知道使用模型中的方法很容易做到这一点,但我希望它是一个关联,以便我可以使用 include 在查询中预加载它.

楷模:

class Product < ActiveRecord::Base
    has_many :image_associations, :as => :imageable
    has_many :images, :through => :image_associations
end

class ImageAssociation < ActiveRecord::Base
    belongs_to :image
    belongs_to :imageable, :polymorphic => true
end

class Image < ActiveRecord::Base
    has_many :image_associations
end

在 ImageAssociation 表中,有一个名为“feature”的 bool 列,它将图像关联为“主”图像。

我考虑过这样做的方法之一是添加 main_image_id列到产品表,然后添加到 Image模型:
belongs_to :image, :class => "Image", :foreign_key => "main_image_id"

但是,如果主图像为零,这不允许回退到其他 has_many 图像——我希望关联加载。

这就是为什么我希望图像模型中有一些东西,例如:
has_one :image, :through => :images, :conditions => 'feature = true', :order => 'created_at DESC'

但这给了我一个关联错误。

有什么方法可以编辑 has_one,还是我真的需要运行 rake 任务将图像推送到每个 main_image_id 字段,然后为 future 的产品添加验证以确保已添加主图像?

编辑:

我应该使用 has_and_belongs_to_many协会代替?

最佳答案

你快到了,我想,虽然我对多态关联不是很清楚。我想你想要以下内容:

has_one :main_image_assoc, class => "ImageAssociation", :conditions => 'feature = true', :order => 'created_at DESC', :as => :imageable
has_one :image, :through => :main_image_assoc

关于ruby-on-rails - rails has_one 一个 has_many 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9840169/

相关文章:

ruby-on-rails - 未指定数据库文件。缺少参数 : database

mysql - 在 Rails 查询中指定条件包括不起作用

php - 有没有办法在 laravel 模型中访问关系属性作为自己的?

ruby-on-rails - 设置虚拟支付网关以在 Rails 中进行测试

ruby-on-rails - 实例化创建 HTTP 请求时类的测试方法

ruby-on-rails - Rails 5 ActiveRecord - 在使用方法之前检查是否有任何结果

php - Magento、getSubtotal 和 getGrandTotal 始终返回零

php - Cakephp "virtual"与另一个数据库一起使用的模型名称

ruby-on-rails - 运行 `gem pristine --all` ... 将提高 Spring 的启动性能。 (实际上并没有这样做)

mysql - 如何在 ruby​​ on Rails 中动态添加列到现有数据库