开发者

ruby on rails fetch activerecords with where clause

开发者 https://www.devze.com 2023-03-10 06:55 出处:网络
I have a simple question - basically I want to fetch all ActiveRecords of some model X which adhere to some conditions. I am trying to use the X.where method here but I am not sure how it will work. B

I have a simple question - basically I want to fetch all ActiveRecords of some model X which adhere to some conditions. I am trying to use the X.where method here but I am not sure how it will work. Basically, m开发者_Go百科y model X has_many Y.

I have a list of ids for model Y objects. I want to find all of model X which has at least one of those ids in its has_many Y.

Is there a simple way I can do this using X.where? Or do i need more complicated sql?


Here is what I would do:

Modelx.joins(:modelys).where(:modelys => { :id => list_of_ids }).all 

Another solution that I prefer is to use scopes:

def Modelx < ActiveRecord::Base
  has_many :modelys
  has_many :modelzs

  scope :has_modely_ids, lambda { |ids| joins(:modelys).where(:modelys => { :id => [*ids] }) }
  scope :has_modelz_ids, lambda { |ids| joins(:modelzs).where(:modelzs => { :id => [*ids] }) }

end

then you can do stuff like:

Modelx.has_modely_ids(y_ids).all
Modelx.has_modelz_ids(z_ids).all

modelx_with_ys = Modelx.has_modely_ids(y_ids)
modelx_with_zs = Modelz.has_modely_ids(y_ids)

or chaining: (just rememeber to call all when you actually want to run the query)

modelx_with_y_and_zs = Modelx.has_modely_ids(y_ids).has_modelz_ids(z_ids)
modelx_with_y_and_zs = modelx_with_ys.has_modelz_ids(z_ids)
0

精彩评论

暂无评论...
验证码 换一张
取 消