[英]Rails find records tagged with multiple tags | undefined method 'where' for Array
所以我想建立一个工作板,其中包含可标记的工作。 我想自己实现,所以我跟着这个教程: https : //www.sitepoint.com/tagging-scratch-rails/
一切正常,但我不仅想获得所有标有一个标签的工作(本教程有一种用于该tagged_with(name)
),而且我想获得所有标有多个标签的工作。
所以我在job.rb
模型中添加了一个方法,如下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>
这是我的模型:
工作.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
作业标签
class Jobtag < ActiveRecord::Base
has_many :taggings
has_many :jobs, through: :taggings
end
标签文件
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')
更新
如果要获取包含在@tags 数组中列出的所有标签的作业,请检查同一查询中的作业标签计数。
@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')
希望能帮助到你 !
要使用.where
您需要有一个 ActiveRecord 集合。
Job.joins(:job_tags).where("jobs_tags: { name: "name of tag or array of tag names").where(category: 'Full-Budget').order('created_at desc')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.