Rails active record - a condition for difficult conditions

it works:

ids = [1,2]
varietals = Varietal.find(:all, :conditions => [ "id IN (?)",ids])

But I want to say that the plus has a condition: deleted => false

varietals = Varietal.find(:all, :conditions =>{ :deleted => false})

any ideas?

Do I have to use find_by_sql?

+3
source share
3 answers

You can do this in several ways, but it is most straightforward:

varietals = Varietal.find( [1,2], :conditions => { :deleted => false })

You can see in the docs that the first parameter findcan take an integer or an array.

+3
source

I would handle this with named_scope to communicate intentions and facilitate reuse:

named_scope :undeleted,
            :conditions => { :deleted => false }

Then you can simply use:

varietals = Varietal.undeleted.find([1,2])
+5
source
ids = [1,2]
varietals = Varietal.find(:all, :conditions => {:id => ids, :deleted => false})

, .

docs:

SQL IN:

Student.find(:all, :conditions => { :grade => [9,11,12] })
+2
source

Source: https://habr.com/ru/post/1727908/


All Articles