簡體   English   中英

Rails 查找帶有多個標簽的記錄 | 數組的未定義方法“where”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM