2012-11-17 72 views
1

我使用rails 3.0.3。 我有4張桌子。紅寶石在rails-使用範圍內的聯盟

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將其放在「抽象」的地方藝術品範圍:

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'; 

謝謝!

回答

1

它有點遲了,但這可能對某人有所幫助。最後,找到了導軌的做法。

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.*") 
} 
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}') 
" 
}