HABTM关系-如何根据关联模型的属性查找记录 [英] HABTM Relationship -- How Can I Find A Record Based On An Attribute Of The Associated Model

查看:73
本文介绍了HABTM关系-如何根据关联模型的属性查找记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我过去已经建立了这种 HABTM 关系,并且在...之前起作用了....现在还没有,我正竭尽全力试图找出问题所在.我整天浏览着导轨,似乎无法弄清楚我在做什么错,因此非常感谢您的帮助.

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 through the rails guides all day and can't seem to figure out what I'm doing wrong, so help would really be appreciated.

我有2个通过联接模型连接的模型,我试图根据相关模型的属性查找记录.

I have 2 models connected through a join model and I'm trying to find records based an attribute of the associated model.

Event.rb

has_and_belongs_to_many :interests

Interest.rb

Interest.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 ] )

但是得到了错误:

未找到名为兴趣"的协会;也许您拼错了?"

"Association named 'interest' was not found; perhaps you misspelled it?"...

我没有偏离路线.

我尝试过:

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

但收到错误:

#Class:0x4383348的未定义方法'interests'"

"undefined method `interests' for #Class:0x4383348"

如何找到兴趣ID为4的事件.

How can I find the Events that have an interest id of 4....I'm definitely going bald from this lol

推荐答案

您需要包括兴趣表.

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

您在帖子中说的没错,但您没有使兴趣多元化.

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

更新

由于此答案仍然受到关注,我认为使用ActiveRecord::Relation语法更新它可能是一个好主意,因为上述方法将不建议使用.

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 })

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

如果您需要自定义条件

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

这篇关于HABTM关系-如何根据关联模型的属性查找记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆