简体   繁体   中英

Rails 4 – habtm relation with condition on query?

I currently have three models:

  • Tags (habtm: Posts)
  • Posts (habtm: Tags and has many Images)
  • Images (belongs to Post)

I want, tag-controller, get all posts in relationship with the tag , that has relations some to images.

Kinda of like:

Tag.posts.where("images").nil? (of course not like this, but I hope you see where I'm heading)

First of, I'm really new to Rails, and haven't done any query conditions on my models (only *.all or *.find)

of course I could fetch all posts belonging to the tag, loop through the posts and remove those that don't have an image relation, but that doesn't seem right ;)

* EDIT:
Perhaps i was unclear, i would like to get all tags (Tags.all()) that has relation with a post, that has relation with an image.
More like: Tags.all.posts.images != null ;) *

You can do it this way:

Tag.joins(posts: :images)

This will load all tags that have posts that have images.

Checking for the existence of a related record is easy in SQL but there's not an "easy" syntax in Rails for it, as far as I know. The trouble with a simple join is that a post having n images will appear in the result set n times -- you can perform a distinct on the result, but that gets increasingly less efficient with increased data sets.

Tag.joins(:posts).where("exists (select null from images where images.post_id = posts.id)")

Similarly, tags for posts with no image:

Tag.joins(:posts).where("not exists (select null from images where images.post_id = posts.id)")

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