簡體   English   中英

Rails 4 has_many通過

[英]Rails 4 has_many through

我在Rails 4中有以下代碼:

  POST_MODEL_TO_INT = {text_post: 1, video_post: 2}

  class Label < ActiveRecord::Base
  end

  module PostBase
    include do
      has_many :posts_to_labels, :foreign_key => :post_id, :conditions => { post_model_id: POST_MODEL_TO_INT[self.name.underscore.to_sym] }
      has_many :labels, :through => :posts_to_labels
    end
  end

  class TextPost
    include PostBase
  end

  class VideoPost
    include PostBase
  end

  class PostsToLabel < ActiveRecord::Base
    belongs_to :post
    belongs_to :label
  end


  TextPost.first.labels => return labels collection

我必須添加什么Label才能從標簽實例中獲取所有帖子?

Label.first.posts # -> return collection of posts Video, Text ....
Label.first.text_posts # -> return collection of posts Text .... 
class Label < ActiveRecord::Base
  has_many :posts_to_labels, :conditions => { post_model_id: 2 }
  has_many :text_posts, :through => :posts_to_labels
end

class PostsToLabel < ActiveRecord::Base
  belongs_to :post
  belongs_to :label
  belongs_to :text_post, :foreign_key => :post_id
end

我找到單一資源的解決方案,但不明白為什么我需要在hassmany中添加PostsToLabel嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM