0

私はこのような非常に単純なモデルを持っています:

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 

これにより、Cookies テーブルを介してこのユーザーに関連付けられたすべての運勢が得られます。私がやりたいことは、によって返されなかったすべてのフォーチュンを取得することですu.fortunes

私は試した

Fortune.all(:limit => 5, :conditions => {:user => {:id._ne => u.id} })

しかし、それは機能しません:(。私はActiveRecordを初めて使用します。

ありがとう

4

4 に答える 4

1

これを試して:

Fortune.limit(5).where("id not in (?)", u.fortunes.map(&:id))

(自分のテーブルで試してみました)

于 2012-11-26T01:54:39.423 に答える
0

またはこれを試してください

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:usersを使用しない理由は、1つの余分な結合を回避するためです。

編集: 他の提案はより短く、(結合なしで)見つけるときにも少し速くなると思います。私は関連付けの使用方法を示したかっただけです。

于 2012-11-26T01:54:32.717 に答える
0

これを試して

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

ユーザーに属する運勢を削除し、残りを私たちに提供します。

于 2012-11-26T13:00:14.320 に答える
0

できるよ

ids_to_reject = u.fortunes.map(&:id)
Fortune.all(:limit => 5, :conditions => ["id not in (?)", ids_to_reject])
于 2012-11-26T01:38:32.827 に答える