简体   繁体   中英

Querying through associations

I have a Step model and an Images model; the association between Steps and Images is that an Image belongs to a Step, and Steps have many images. I'd like to query steps where it returns all the steps that have more than one image. How would I do this in the rails console?

I've tried the following:

Step.where("images > ? ", 1)
Step.joins(:images).where("image.count > 1")

and neither work.

Many thanks!

I can give you similiar query from my app so you would excercise your brain a little ;)

Activity.joins(:slots).group('activities.id').having('COUNT(activity_id) > 1')

Ok, what you should do

Step(:images).group('steps.id').having('COUNT(images.step_id) > 1')

which is EXACTLY my example but with changed model names.

Maybe something like this?:

Step.find(:all, 
          select: "steps.*, count(images.id) as image_count", 
          joins: :images, 
          having: "image_count > 1", 
          group => 'images.step_id')

Check this explanation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM