Rails 4, ActiveRecord. Join table and select by different records of one
model of joined table
Models:
class Option < ActiveRecord::Base
belongs_to :estate
belongs_to :metric
...
end
class Estate < ActiveRecord::Base
belongs_to :category
has_many :options, :dependent=>:destroy
...
end
class Category < ActiveRecord::Base
has_many :estates, :dependent=>:destroy
has_many :metrics, :dependent=>:destroy
...
end
class Metric < ActiveRecord::Base
belongs_to :category
has_many :options, :dependent=>:destroy
...
end
I can find Estate with given params of option by:
Estate.where(bla: 'bla-bla').joins(:options).where('options.metric_id=?
and options.field1=?', 1,'bla-bla')
But each Estate has many Options, how can i select Estate with one value
of one option and second value of another option by sql or ActiveRecord,
like:
Estate.where(bla: 'bla-bla').to_a.
select{|x| x.options.exists?(metric_id: 1, field1: 'value1')
&& x.options.exists?(metric_id: 2, field1: 'value2')}
No comments:
Post a Comment