1
以下のように@ user.connectionsを呼び出すと、なぜ接続テーブルが更新されるのですか?ActiveRecordポリ付加配列対連結配列
class User < ActiveRecord::Base
has_many :left_connections, :as => :left_nodeable, :class_name => 'Connection', :conditions => {:left_nodeable_type => 'User', :right_nodeable_type => 'User'}
has_many :right_connections, :as => :right_nodeable, :class_name => 'Connection', :conditions => {:right_nodeable_type => 'User', :left_nodeable_type => 'User'}
def connections
self.left_connections << self.right_connections
end
end
私が使用している場合
接続モデル
class Connection < ActiveRecord::Base
belongs_to :left_nodeable, :polymorphic => true
belongs_to :right_nodeable, :polymorphic => true
# Statuses:
PENDING = 0
ACCEPTED = 1
named_scope :pending, :conditions => { :connection_status => PENDING }
named_scope :accepted, :conditions => { :connection_status => ACCEPTED }
end
ユーザーモデル:
def connections
self.left_connections + self.right_connections
end
次にモデルがOKに動作しますが、私は私のnamed_scope方法のいずれかを使用することはできません。
だから私は、私の質問を推測が
...に沸くのActiveRecordの「< <」と「+」演算子の違いは何ですか?なぜ "< <"を使用するとデータベースが変更され、named_scopeメソッドが失敗する "+"原因がありますか?
ありがとうGarrett。私は、接続モデルで失敗したいくつかの名前付きスコープで質問を更新しました。 "@ user.connections.pending?"を呼び出すにはどうすればいいですか? – BenB
ああ、問題は.connections()が配列を返し、配列にスコープを使用できないということです。代わりに ' @ user.connections.reject {| c | c_connection_status == ACCEPTED} ' –
を返すか、'(user_id =? '、user_id)を返す接続クラスメソッド/スコープ 'self.with_user(user_id) (例えば、 'Connection.with_user(@ user.id).pending')。レール3の構文は残念ですが、レール2のクエリを使用してからしばらくしています –