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

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

问题描述

过去我已经建立了这个HABTM关系,之前它的工作已经完成了....现在,我不知道什么是错的。我一整天都在查看导轨指南,而且似乎无法弄清楚我做错了什么,所以帮助真的很感谢。



我有2个模型连接通过一个连接模型,我试图找到相关模型的属性的记录。



Event.rb

  has_and_belongs_to_many:interest 

Interest.rb

  has_and_belongs_to_many:events 

以及创建的连接表迁移

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

我试过了

$ p $ @events = Event.all(:include =>:interest,:条件=> [interest.id =?,4])

没有找到名为兴趣的协会,也许你拼错了?我当然没有这样做......我试过了

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

但是得到错误未定义的方法`兴趣'为#Class:0x4383348



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

解决方案

您需要包含兴趣表。

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

您在文章中的权利是正确的,但是您没有将利益复数化。

更新



因为这个答案仍然受到关注,所以我认为使用 ActiveRecord :: Relation


$ b

  @events = Event.includes(:兴趣)。(interest:{id:4})

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


I have setup this HABTM relationship in the past and its worked before....Now it isnt and I'm at my wits end trying to figure out whats wrong. I've looking through the rails guides all day and cant seem to figure out what I'm doing wrong, so help would really be appreciated.

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

has_and_belongs_to_many :events

and a join table migration that was created like

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

I tried

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

But got the error "Association named 'interest' was not found; perhaps you misspelled it?"... which I didnt of course

I tried

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

but got the error "undefined method `interests' for #Class:0x4383348"

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

解决方案

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)

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

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