Rails 查找带有多个标签的记录 |数组的未定义方法'where'



所以我想建立一个工作板,其中包含可标记的工作。我想自己实现它,所以我按照本教程进行操作:https://www.sitepoint.com/tagging-scratch-rails/

所有

工作,但我不仅想获得所有用一个标签标记的作业(本教程有一个针对该tagged_with(name)的方法(,而是我想获取所有用多个标签标记的作业。

所以我在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

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

更新

如果要获取数组中列出了所有标记@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')

最新更新