Rails查找使用多个标记标记的记录|未定义的方法,其中适用于阵列 [英] Rails find records tagged with multiple tags | undefined method 'where' for Array
本文介绍了Rails查找使用多个标记标记的记录|未定义的方法,其中适用于阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我想构建一个工作板,其中的工作是可标记的。 我想自己实现它,所以我遵循了以下教程: https://www.sitepoint.com/tagging-scratch-rails/
所有作业都有效,但我不仅希望获取使用一个标记(本教程提供了该方法)的所有作业,而且还希望获取使用多个标记进行标记的所有作业。
因此我向job.rb
模型添加了一个方法,如下所示:
def self.tagged_with_tags(tags)
jobs = []
tags.each do |tag|
Jobtag.where(name: tag).first.jobs.map do |j|
jobs.push(j) unless jobs.include?(j)
puts j
end
end
jobs
end
这似乎是可行的,但我想进一步查询返回的数组:
@jobs = Job.tagged_with_tags(@tags).where(category: 'Full-Budget').order('created_at desc')
下面我得到了这个错误:
undefined method 'where' for #<Array:0x007fb1b0a25c10>
以下是我的模特:
job.rb
class Job < ActiveRecord::Base
has_many :taggings
has_many :jobtags, through: :taggings
def all_jobtags=(names)
self.jobtags = names.split(",").map do |name|
Jobtag.where(name: name.strip.downcase).first_or_create!
end
end
def all_jobtags
self.jobtags.map(&:name).join(", ")
end
def self.tagged_with(name)
Jobtag.find_by_name!(name.downcase).jobs
end
# Needs work:
def self.tagged_with_tags(tags)
jobs = []
tags.each do |tag|
Jobtag.where(name: tag).first.jobs.map do |j|
jobs.push(j) unless jobs.include?(j)
puts j
end
end
jobs
end
end
Jobtag.rb
class Jobtag < ActiveRecord::Base
has_many :taggings
has_many :jobs, through: :taggings
end
Tagging.rb
class Tagging < ActiveRecord::Base
belongs_to :job
belongs_to :jobtag
end
推荐答案
您可以使用活动记录联接查询获得所需的结果。 循环访问每个作业对象并将其推送到数组的效率较低。
@tags = ['tag_name1', 'tag_name2']
类似以下内容:
@jobs = Job.joins(:jobtags).where(jobtags: { name: @tags }).
where(category: 'Full-Budget').
order('created_at desc')
更新
如果要提取所有标记都列在@tag数组中的作业,请检查同一查询中的作业标记计数。
@jobs = Job.joins(:jobtags).where(jobtags: { name: @tags }).
group('jobs.id').
having('count(jobs.id) = ?', @tags.size).
where(category: 'Full-Budget').
order('created_at desc')
希望能有所帮助!
这篇关于Rails查找使用多个标记标记的记录|未定义的方法,其中适用于阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文