How to query array columns in Rails 4? -


i can't find articles how query array columns in rails. came across need query array column in rails.

i found article teaching how basic query here.

let's follow example in article book covers many subjects , subjects stored array column:

add_column :books, :subjects, :text, array: true, default: [] 

query books contains subject - e.g. history

book.where("'history' = (subjects)") 

query books contains listed subjects - e.g. finance , business , accounting

book.where("subjects @> ?", "{finance,business,accounting}") 

i wonder how can following?

query books contains of listed subjects - e.g. fiction or biography

query books doesn't contain subject - e.g. not physics

query books doesn't contain of subjects - e.g. not (physics or chemistry or biology)

and there rails way of doing above queries?

  1. don't store arrays in db. ever. there better solution (associations):

    book has_many :subjects # or has_one/has_and_belongs_to_many

    subject belongs_to :book # or has_and_belongs_to_many

    and create table subjects, save subjects there , you're set up. retrieving data array columns in db really slow , non-effective.

  2. your queries:

query books contains of listed subjects - e.g. fiction or biography

book.find_by_sql "select * books 'fiction' = (subjects) or 'biography' = (subjects)" 

query books doesn't contain subject - e.g. not physics

book.where.not("subjects @> ?", "{physics}") 

query books doesn't contain of subjects - e.g. not (physics or chemistry or biology)

book.find_by_sql "select * books books not in (select * books 'physics' = (subjects) or 'chemistry' = (subjects) or 'biology' = (subjects)" 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -