【问题标题】:HABTM Relationship -- How Can I Find A Record Based On An Attribute Of The Associated ModelHABTM 关系——如何根据关联模型的属性找到记录
【发布时间】:2011-01-14 00:47:59
【问题描述】:

我过去已经设置了这种 HABTM 关系,它以前也有效....现在它不是,我正在努力找出问题所在。我整天都在查看 rails 指南,但似乎无法弄清楚我做错了什么,因此非常感谢您的帮助。

我有 2 个模型通过连接模型连接,我正在尝试根据关联模型的属性查找记录。

事件.rb

has_and_belongs_to_many :interests

利息.rb

has_and_belongs_to_many :events

以及创建的连接表迁移如下:

create_table 'events_interests', :id => false do |t|
    t.column :event_id, :integer
    t.column :interest_id, :integer
end

我试过了:

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

但是得到了错误:

“未找到名为‘interest’的关联;也许你拼错了?”...

我没有偏离路线。

我试过了:

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

但得到了错误:

“#Class:0x4383348 的未定义方法‘interests’”

我怎样才能找到兴趣 id 为 4 的事件....我肯定会因为这个大声笑而秃头

【问题讨论】:

    标签: ruby-on-rails find has-and-belongs-to-many


    【解决方案1】:

    您需要包含兴趣表。

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

    您在帖子中说得对,但您没有将兴趣多元化。

    更新

    因为这个答案仍然受到关注,我认为使用ActiveRecord::Relation 语法更新它可能是一个好主意,因为上述方式将被弃用。

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

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

    如果您需要自定义条件

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

    【讨论】:

    • #includes 将提取所有“兴趣”对象。如果您只想过滤,还有另一种方法#joins,它只会进行过滤。
    【解决方案2】:

    答案很有帮助,谢谢!我知道这篇文章很旧,但我想出了一个可能对某人有用的不同解决方案。我注意到在我的情况下查询生成很长。对我来说,与您的“兴趣”表相等的表中有很多列和数据。为了避免在该表中搜索匹配的 id,我的解决方案类似于:

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

    这对我有用,因为我已经有一个带有事件 ID 列表的实例化 @interest 对象。当然,您并没有使用 rails 提供的一些魔法。另外,我无法让您的解决方案与“不”一起使用。例如;

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

    行不通。它将返回 0 个结果。但是这个:

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

    会起作用,这将返回所有与@interest 没有关联的事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      相关资源
      最近更新 更多