Rails如何在多个关联级别上检索act-as-taggable-on标记

时间:2017-03-14 14:45:00

标签: ruby-on-rails ruby postgresql

摘要

我的acts_as_taggable_on :skills模型中有Ad.rb。 我有以下关系:

主机型号has_many :locations

位置has_many :ads

广告acts_as_taggable_on :skills

我需要主持技能列表。对于每个主持人,我需要通过他的广告检索他所拥有的技能列表 enter image description here

我需要查询它们,而且我不知道如何使用ActsAsTaggableOn对象进行查询。

我所知道的

我可以轻松检索Location(数字2)的所有技能。每个主机都可以有多个位置。

Location.ads.tag_counts_on(:skills)

此查询会返回一个对象,其中包含Location Skills=> [#<ActsAsTaggableOn::Tag:0x0000000943b878 id: 6, name: "javascript", taggings_count: 4>, #<ActsAsTaggableOn::Tag:0x0000000943b738 id: 4, name: "css", taggings_count: 6>, #<ActsAsTaggableOn::Tag:0x0000000943b5f8 id: 8, name: "rubyonrails", taggings_count: 2>] ,结果如下:

=> ActsAsTaggableOn::Tag::ActiveRecord_Relation

这是这个对象的类:

.find()

在这个类上,我可以调用像.find()这样的方法,但是如果我在数组中复制这些数据,那么我就无法执行skills = ["css","html","javascript"] 查询,来检查我是否添加了副本。

我只需要一系列这样的技能,如:

@developers = Developer.tagged_with(skills, :any => :true)

这样我就可以执行此查询:

use XML::Simple;
use Data::Dumper;

my $file1_ref = XMLin("./file1");
my $file2_ref = XMLin("./file2");

if($file2_ref->{NetworkDeviceIPList}->{NetworkDeviceIP}->{ipaddress} eq $file1_ref->{entity}->{devicesDTO}->{ipAddress} && $file2_ref->{name} eq $file1_ref->{entity}->{devicesDTO}->{deviceName}) {
  print "WebService1 already contains DeviceName \"".$file2_ref->{name}."\"\n";
} else {
  # POST request and add this device in WebService1/WebService2
  # Code here ....                                                                                                                                                                                                                                                              
}

最后一个查询有效,我只需要找出检索技能的最佳方法。

这是gem github页面上的acs-as-taggable https://github.com/mbleigh/acts-as-taggable-on

我还添加了这个项目的 git https://github.com/fabriziobertoglio1987/SocialNetwork

非常感谢 的Fabrizio

1 个答案:

答案 0 :(得分:3)

怎么样?
class Host
  has_many :ads, through: :locations
  has_many :skills, through: :ads
end

host = Host.first
skills = host.skills.pluck(:name)
@developers = Developer.tagged_with(skills, any: :true)