[英]Rails 4 has_many through
I have the following code in Rails 4: 我在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
What must I add to the Label
model to get all and each post from a label instance? 我必须添加什么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
I find solution for single resource, but don't understood why i need add has_many to PostsToLabel ? 我找到单一资源的解决方案,但不明白为什么我需要在hassmany中添加PostsToLabel吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.