2014-06-21 65 views
0

我試過圍繞如何瀏覽我想要的關聯,但我似乎無法弄清楚。我試圖得到Tag的所有Posts。每個帖子目前都有一個標題和正文文本,這兩個文本都表示爲TaggedText。每個TaggedText都可以有許多獨特的標籤 - 例如在Facebook帖子中標記多個人/頁面(保存實例時在模型中實施唯一性)。Rails:跨多個協會提取模型

class Tag < ActiveRecord::Base 
    has_many :tagged_texts, through: :tag_ranges 
end 
class Post < ActiveRecord::Base 
    has_many :tagged_texts 
end 
class TaggedText < ActiveRecord::Base 
    # Each TaggedText cannot have more than one of each tag 
    has_many :tags, through: :tag_ranges 
    belongs_to :post 
end 
class TagRange < ActiveRecord::Base 
    # TaggedText cannot have more than one of each tag 
    belongs_to :tagged_text 
    belongs_to :tag 
end 

我試圖連接表,但我得到的錯誤Association named 'tag_ranges' was not found on Post

def get_posts_by_tag(tag, page, posts_per_page) 
Post 
    .joins(:tagged_texts) 
    .joins(:tag_ranges) 
    .joins(:tags) 
    .where('tag.id = ?', tag.id) 
    .uniq 
    .limit(posts_per_page) 
    .offset(page - 1) 
    .to_a 
end 

我缺少的是讓查詢工作 - 或者我應該調整自己的模型和關聯不知何故?

回答

1

當您錯誤狀態時,您需要將tag_ranges關聯添加到您的Post模型。我還添加了一些可能會或可能不會有用的關聯,並且會大大簡化您的查詢。不是你的TagRange類的關聯是好的。

class Tag < ActiveRecord::Base 
    has_many :tag_ranges # need this association in order to get tagged_texts 
    has_many :tagged_texts, through: :tag_ranges 
    has_many :posts, -> { uniq }, through: :tagged_texts # posts with the given tag 
end 

class Post < ActiveRecord::Base 
    has_many :tagged_texts 
    has_many :tag_ranges, through: :tagged_texts # Post now has association named 'tagged_ranges' 
    has_many :tags, -> { uniq }, through: :tag_ranges # tags that given post has 
end 

class TaggedText < ActiveRecord::Base 
    has_many :tag_ranges # all tag ranges for a tag text 
    has_many :tags, through: :tag_range 
    belongs_to :post 
end 

而現在,你的查詢以獲取標籤的所有帖子:

def get_posts_by_tag(tag, page, posts_per_page) 
    tag.posts.limit(posts_per_page).offset(page - 1).to_a 
end 

希望這有助於!

+0

奇妙的,完美的作品。謝謝喬!出於好奇,lambda在做什麼:' - > {uniq}'?這只是對系統的「暗示」,或者是ActiveRecord實際執行某些事情?我從來沒有見過lambda記錄,你能找到一個鏈接到它的文檔? – FeifanZ

+0

此外,在'標記'你添加關聯'has_many:tag_ranges',顯然獲得'tagged_texts' ...爲什麼該關聯獲得'tagged_texts',而'has_many:tagged_texts,通過::tag_ranges'不? – FeifanZ

+1

我還沒有找到' - > {}'的官方文檔,這個文檔叫做作用域塊,但是你可以在[本Rails指南]中找到關於它的一些信息(http://guides.rubyonrails.org/ association_basics.html#範圍換擁有多)。它本質上是爲你的關聯定義一個範圍。在這種情況下,它意味着當獲得這個帖子的標籤時,只返回唯一的標籤。 –