HABTM Relationship — How Can I Find A Record Based On An Attribute Of The Associated Model

后端 未结 2 1521
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 18:00

I have setup this HABTM relationship in the past and it has worked before....Now it isn\'t and I\'m at my wits end trying to figure out what\'s wrong. I\'ve looked

2条回答
  •  旧时难觅i
    2020-12-13 18:35

    The answer was helpful, thanks! I know this post is old, but I came up with a different solution that might be useful to someone. I noticed the query generate was quite long in my case. For me the table that was equatable to your "interests" table had a lot of columns and data in it. To avoid searching that table for the matching id, my solution looked similar to this:

    @events = Event.all.where('events.id' => @interest.events.each(&:id)) 
    

    This worked for me since I already had an instanced @interest object with the list of ids for the events. Of course you're not using some of the magic the rails has available. Also, I couldn't get your solution to work with "not". For example;

    @events = Event.includes(:interests).where.not(interests: { id: 4 })
    

    would not work. It would return 0 results. But this:

    @events = Event.all.where.not('events.id' => @interest.events.each(&:id)) 
    

    would work, which would return all the the events that don't have an association with @interest.

提交回复
热议问题