2013-06-25 55 views
0

我在轨道4,5下面的代码:轨道4的has_many通过

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 .... 
+0

它真的好像你正在重塑[多态关联](http://guides.rubyonrails.org/association_basics.html#polymorphic-associations)。 – meagar

+0

是的,我认为相同,但不幸的是,我可以; t改变发布资源代码 – Alex808

回答

0
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 

我找到一个资源解决方案,但不明白为什么我需要补充的has_many到PostsToLabel?