Rails:acts-as-taggable-on:在关系上使用tags_with [英] Rails:acts-as-taggable-on: Using tagged_with on a relation

查看:93
本文介绍了Rails:acts-as-taggable-on:在关系上使用tags_with的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个模型A,该模型与模型B有1:1的关联。模型B设置为 acts_as_taggable。我想返回一个活动记录关系,该关系选择所有B属性被标记为带有特定字符串的A实例。看起来像:
A.where('b.tagged_with =?','some_tag')

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')

我发现这个 SO问题,但我有兴趣返回活动记录关系,因此仅第二种解决方案适用,而我无法使其正常工作。如何获取活动记录关系,以便可以在其上调用其他查询参数方法。 A.b_tagged_with('tag')。where(...),其中b_tagged_with是一个命名范围

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

推荐答案

来回答我自己的问题问题,我在A中的范围定义如下:

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]
    }
  }

这表示如果标签的标签关联的名称值等于我们传递的参数,则返回所有b成员与该标签相关联的A模型。在此示例B中, acts_as_taggable不为A。
这允许我执行以下操作:

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

这篇关于Rails:acts-as-taggable-on:在关系上使用tags_with的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆