Rails:acts-as-taggable-on: Using tagged_with on a relation

感情迁移 提交于 2019-12-23 05:26:54

问题


Lets say I have a Model A which has a 1 to 1 association with Model B. Model B is set to 'acts_as_taggable'. I would like to return an active record relation that selects all A instances who's B attribute is tagged_with a certain string. It would look something like: A.where('b.tagged_with = ?', 'some_tag')

I found this SO question, but i'm interested in getting an active record relation back so only the 2nd solution is applicable and I can't get it to work. How can I get back active record relations so I can call other query params methods on it ie. A.b_tagged_with('tag').where(...) where b_tagged_with is a named scope


回答1:


to answer my own question, my scope definition in A looks like this:

    scope :tagged_with, lambda { |tag|
    {
        :joins => "INNER JOIN taggings ON taggings.taggable_id = as.b_id\
                   INNER JOIN tags ON tags.id = taggings.tag_id AND taggings.taggable_type = 'B'",
        :conditions => ["tags.name = ?", tag]
    }
  }

What this says is return all A models whose b members are associated with a tagging if that taggings' tag association has a 'name' value equal to the param we passed in. In this example B 'acts_as_taggable', A doesn't. This allows me to do:

a = A.new
b = B.new
b.tag_list = ['tag1', 'tag2', 'tag3']    
a.b = b
new_a = A.tagged_with('tag1').ordered(...
#At this point new_a.last == a


来源:https://stackoverflow.com/questions/8584806/railsacts-as-taggable-on-using-tagged-with-on-a-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!