Belongs_to与where条件

时间:2016-03-09 15:26:32

标签: ruby-on-rails ruby

我有以下情况:

横幅有1个附件,其中一个有很多孩子(称为附件)。然后我需要得到附件和他的孩子(我已经得到的)。但我只想要具有mime_type == 'image. (jpg/jpeg)'或任何类型图像的附件(父母和子女)。

模特(工作)

class Admin::Banner < ActiveRecord::Base
    belongs_to :attachment, -> { includes :attachments }, foreign_key: :admin_attachment_id, class_name: 'Admin::Attachment'        
    has_many :attachments, through: :attachment
end

我正在尝试使用以下代码获取具有该条件的附件,但它不起作用:

belongs_to :attachment, -> { includes :attachments, where "mime_type REGEXP 'image.*'" }, foreign_key: :admin_attachment_id, class_name: 'Admin::Attachment'

1 个答案:

答案 0 :(得分:0)

我修复了以下代码:

class Admin::Banner < ActiveRecord::Base
    belongs_to :attachment, -> { where "admin_attachments.mime_type REGEXP 'image.*'" }, foreign_key: :admin_attachment_id, class_name: 'Admin::Attachment'
    has_many :attachments, through: :attachment
end