Ruby on rails ActiveRecord找不到(有多个)

Ruby on rails ActiveRecord找不到(有多个),ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有这样一个非常简单的模型: 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

我有这样一个非常简单的模型:

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
这将通过Cookies表为我提供与此用户相关的所有财富。我想做的是得到所有不是由
u.Fortunes
返回的财富

我试过了

Fortune.all(:limit => 5, :conditions => {:user => {:id._ne => u.id} })
但这不起作用:(.我对ActiveRecord是新手

谢谢

你能行

ids_to_reject = u.fortunes.map(&:id)
Fortune.all(:limit => 5, :conditions => ["id not in (?)", ids_to_reject])
或者试试这个

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 ])
不使用include的原因:用户是为了避免一个额外的连接

编辑: 其他建议比较简短,我认为在查找(无连接)时也会快一点,我只想展示如何使用关联。

尝试以下方法:

Fortune.limit(5).where("id not in (?)", u.fortunes.map(&:id))
(我在自己的桌子上试过)

试试这个

    @fortune=Fortune.find(:all).delete_if{|fortune| !fortune.user.nil? }

它将删除属于用户的财富,并为我们提供剩余的财富。

I get:Mysql2::Error:where子句中的未知列“users\u id”:选择
fortunes
*FROM
fortunes
where(users\u id!=4或users\u id为NULL)LIMIT 5抱歉,它应该是user\u id(假设您遵循Rails的方式),更新了hanks,有点晚了,但是你现在的方式比'u.fortunes.map(&:id)'方式更有效吗?这取决于。
u.fortunes.map(&:id)
是一读(有两个连接),所以使用它将进行两读(第二次没有连接)。我的建议是一读(有一个连接)。另一方面,如果您在代码中的另一个位置的同一“请求”中使用
u.fortunes
,则不会导致额外的读取。这只在您的表很大时才重要,在这种情况下,您应该在Cookie中的用户id(以及fortune id)上添加索引.没有Rails的方法来代替裸SQL吗?
    @fortune=Fortune.find(:all).delete_if{|fortune| !fortune.user.nil? }