我有一个非常简单的模型,如下所示:
class User < ActiveRecord::Base
has_many :cookies
has_many :fortunes, :through => :cookies
end
class Cookie < ActiveRecord::Base
belongs_to :user
belongs_to :fortune
end
class Fortune < ActiveRecord::Base
has_many :cookies
has_many :users, :through => :cookies
end对于给定的用户u,我可以这样做
u.fortunes 这将给我所有的财富与这个用户通过曲奇表。我想做的是得到u.fortunes没有返还的所有财富。
我试过了
Fortune.all(:limit => 5, :conditions => {:user => {:id._ne => u.id} })但这不起作用:(。我是ActiveRecord的新手。
谢谢
发布于 2012-11-26 09:54:33
或者试试这个
Fortune.includes(:cookies).limit(5).where([ 'cookies.user_id != ? OR cookies.user_id IS NULL', u.id ])或使用您使用的语法
Fortune.all(:include => :cookies, :limit => 5, :conditions => [ 'cookies.user_id != ? OR cookies.user_id IS NULL', u.id ])不使用的原因包括:用户是为了避免一个额外的连接。
编辑:其他的建议都比较短,而且我认为在查找(无连接)时也会更快一点,我只是想展示如何使用关联。
发布于 2012-11-26 09:54:39
试试这个:
Fortune.limit(5).where("id not in (?)", u.fortunes.map(&:id))(我在自己的桌子上试过了)
发布于 2012-11-26 09:38:33
你可以做到
ids_to_reject = u.fortunes.map(&:id)
Fortune.all(:limit => 5, :conditions => ["id not in (?)", ids_to_reject])https://stackoverflow.com/questions/13557537
复制相似问题