我有以下情况:
一个横幅有一个附件,其中一个有很多子项(称为附件)然后我需要得到依恋和他的孩子(我已经得到了)但我只想要有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'

最佳答案

我用以下代码修复:

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

关于ruby-on-rails - 属于有条件的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35895753/

10-11 13:19