为什么在我调用以下@ user.connections时连接表会更新?
连接模型
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
用户模型
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
如果我使用:
def connections
self.left_connections + self.right_connections
end
然后模型工作正常但我不能使用任何我的named_scope方法。
所以我想我的问题归结为......
“&lt;&lt;”之间的区别是什么?和ActiveRecord上的“+”运算符?为什么使用“&lt;&lt;”更改数据库,并使用“+”导致named_scope方法失败?
答案 0 :(得分:2)
模型已更新,因为left_connections已使用<<
方法更新。这使得left_connections = left_connections + right_connections。
arr = [1,2]
arr << [3,4]
arr #=> [1,2,3,4]
-------------------------
arr = [1,2]
arr + [3,4] #=> [1,2,3,4]
arr #=> [1,2]
self.left_connections + self.right_connections
是返回连接的正确方法。至于你的named_scope方法,我无法告诉你为什么他们没有看到它们就失败了。