我有一个可以“关注”某些标签的用户模型
User
has_many :tag_followings
has_many :tags, :through => :tag_followings
然后我有一些文章也贴了一些标签。
Article
has_many :tag_attachings
has_many :tags, :through => :tag_attachings
tag_attaching是一个连接表,其字段为:user_id和tag_id 和tag_following是一个连接表,其字段为:article_id和tag_id
我正在尝试找到一种有效的方法来查找包含用户所关注标记的文章。
最佳做法?
答案 0 :(得分:1)
尝试使用:include 它应该会有很大帮助,因为它会急切地从关联的表中加载记录。
User
has_many :tag_followings
has_many :tags, :through => :tag_followings, :include => [:article]
Article
has_many :tag_attachings
has_many :tags, :through => :tag_attachings, :include => [:user]
您检索数据的语句可能如下所示:
User.find(1).tags.collect { |t| t.article.id }
从log / development.log执行的操作应该来自:
User Load (0.3ms) SELECT users.* FROM users WHERE (users.id = 1) LIMIT 1
Tag Load (1.2ms) SELECT tags.* FROM tags WHERE (users.tag_id =1)
Article Load (3.2ms) SELECT articles.* FROM articles WHERE (articles.tag_id = 1)
Article Load (3.2ms) SELECT articles.* FROM articles WHERE (articles.tag_id = 3)
Article Load (3.2ms) SELECT articles.* FROM articles WHERE (articles.tag_id = 7)
到:
User Load (0.3ms) SELECT users.* FROM users WHERE (users.id = 1) LIMIT 1
Tag Load (1.2ms) SELECT tags.* FROM tags WHERE (users.tag_id =1)
Article Load (3.2ms) SELECT articles.* FROM articles WHERE (articles.tag_id IN (1,3,7))