导轨 - 查找都没有present另一个连接表记录 [英] Rails - Find records that are not present another join table
问题描述
我想写一个ActiveRecord的说明书,我正在寻找的所有记录,其中的id是不是present另一个表...
I'm trying to write a ActiveRecord statment where I'm looking for all records where the id isn't present in another table...
请告诉我的语法?
@events = Event.find(:all, :include => :personals,
:conditions => ["event.id != ? ", @user.personal.event_id ])
在哪里交友是一个连接表具有USER_ID和EVENT_ID ......
Where personals is a join table that has the user_id and a event_id....
所以我基本上是试图找到每一个事件记录用户不添加到自己的一套个人记录......
SO i'm essentially trying to find every event record that the user hasn't added to their own set of personal records....
有没有更好的方式来写这个....不是空的东西?
Is there a better way to write this.... not null or something?
推荐答案
我假设的关系如下:
User:
has_many :personals
has_many :events, :through => :personals
Event:
has_many :personals
has_many :users, :through => :personals
Personal:
belongs_to :event
belongs_to :user
我的解决办法是使用自动创建的关联功能,用户event_ids,列出了所有在User.events的事件id。该查询来获取你所要做的应该是什么:
My solution would be to use the auto-created association function for User "event_ids" that lists all of the event ids in User.events. The query to get what you're trying to do should be:
Event.find(:all, :include => :personals, :conditions => ["events.id NOT IN (?)", @user.event_ids])
和,除非你真正需要的加入,可以简化:
And, unless you actually need the join, you can simplify:
Event.find(:all, :conditions => ["events.id NOT IN (?)", @user.event_ids])
关键是SQL命令,NOT IN(X)。另外,请注意events.id是复数的型号名称,根据SQL约定。
The key is the SQL command, "NOT IN (x)". Also, note the "events.id" is plural for the model name, according to SQL convention.
希望这有助于...
这篇关于导轨 - 查找都没有present另一个连接表记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!