2013-06-25 2 views
0

У меня есть следующий код в Rails 4:Rails 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

Да я думаю, что то же самое, но, к сожалению, я могу, т изменить Почтовый индекс ресурса – 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?