1

我正在使用导轨 3.0.3。我有 4 张桌子。

class Artwork
  has_and_belongs_to_many :tag_styles
  has_and_belongs_to_many :tag_subjects
  has_and_belongs_to_many :tag_arttypes
end

class TagArttype
  set_table_name :tag_arttypes
  has_and_belongs_to_many :artworks
end

class TagStyle
  set_table_name :tag_styles
  has_and_belongs_to_many :artworks
end

class TagSubject
  set_table_name :tag_subjects
  has_and_belongs_to_many :artworks
end

所有这三个 tag_tables 都有一个 name 属性。我如何制作一个接受单词并使用以下 sql 将其放在“Abstract”位置的 Artwork 范围:

select a.* from artworks as a, tag_arttypes as ta, artworks_tag_arttypes as ata where a.id = ata.artwork_id and ta.id = ata.tag_arttype_id and ta.name = 'Abstract' union
 select a.* from artworks as a,tag_styles as ta,artworks_tag_styles as ata where a.id = ata.artwork_id and ta.id = ata.tag_style_id and ta.name = 'Abstract'union
 select a.* from artworks as a,tag_subjects  as ta,artworks_tag_subjects  as ata where a.id = ata.artwork_id and ta.id = ata.tag_subject_id and ta.name = 'Abstract';

谢谢!

4

2 回答 2

1

它有点晚了,但这可能对某人有帮助。最后,找到了 rails 的做法。

scope :by_tags, lambda { |tag|
  includes(:tag_styles,:tag_subjects,:tag_arttypes).where('tag_styles.name LIKE ? OR tag_arttypes.name LIKE ? OR tag_subjects.name LIKE ?',"%#{tag}","%#{tag}","%#{tag}").
 select("DISTINCT artworks.*")
}  
于 2013-09-09T19:32:59.087 回答
0

如果我正确理解您的问题,它非常简单。像下面这样的东西会起作用:

scope :filter, lambda {|name| 
"
 (select a.* from artworks as a, tag_arttypes as ta, artworks_tag_arttypes as ata where a.id = ata.artwork_id and ta.id = ata.tag_arttype_id and ta.name = '#{name}') union
 (select a.* from artworks as a,tag_styles as ta,artworks_tag_styles as ata where a.id = ata.artwork_id and ta.id = ata.tag_style_id and ta.name = '#{name}')  union
 (select a.* from artworks as a,tag_subjects  as ta,artworks_tag_subjects  as ata where a.id = ata.artwork_id and ta.id = ata.tag_subject_id and ta.name = '#{name}')
"
}
于 2012-11-18T14:28:53.803 回答