Question: Rails 4: Advanced Query for Search Interface

Question

Rails 4: Advanced Query for Search Interface

Answers 1
Added at 2017-01-05 16:01
Tags
Question

I need to perform a query on my model that allows me to test an array of tags (belongs_to :recipe)

class Recipe < ActiveRecord::Base
    has_many :taggings, dependent: :destroy
    has_many :tags, through: :taggings
end

class Tag < ActiveRecord::Base
    has_many :taggings, dependent: :destroy
    has_many :recipes, through: :taggings
end

It works when I do:

Recipe.joins(:tags).where("tags.name = ?", 'main course')

but I want to test an array of tags. If I don't use join I can query using an array as follows:

Recipe.where(id: [1, 2, 3])

but it fails when I try:

Recipe.joins(:tags).where(tags.name: ['main course', 'snack'])

How do I fix that final query (postgres db) to allow for an array?

Answers
nr: #1 dodano: 2017-01-06 05:01

Recipe.where(id: [1, 2, 3]) will use in because array of ids are passed.

To make it work with tags.name,

Recipe.joins(:tags).where('tags.name in (?) ', ['main course', 'snack'])

should be used as we are searching from joined relation and not from recipes table.

Source Show
◀ Wstecz