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

后端 未结 2 1525
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  难免孤独
    2020-12-13 18:30

    You need to include the interests table.

    @events = Event.all(:include => :interests, :conditions => ["interests.id = ?", 4])
    

    You had it right in your post, but you didn't pluralize interests.

    Update

    Because this answer is still getting attention, I thought it might be a good idea to update it using ActiveRecord::Relation syntax since the above way is going to be deprecated.

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

    or

    @events = Event.includes(:interests).where('interests.id' => 4)
    

    And in case you want a custom condition

    @events = Event.includes(:interests).where('interests.id >= 4')
    

提交回复
热议问题