1
为什么连接表在我为以下内容调用@ user.connections时得到更新?ActiveRecord多边形阵列与连接阵列
连接模型
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方法。
所以我想我的问题归结为...
是什么在一个ActiveRecord的“< <”和“+”操作符之间的区别?为什么使用“< <”更改数据库,并使用“+”导致named_scope方法失败?
谢谢Garrett。我已经用连接模型中失败的一些命名作用域更新了这个问题。所以剩下的问题就是“我怎么称呼@ user.connections.pending? – BenB 2010-12-30 04:10:40
啊,所以问题是.connections()返回一个数组,你不能在数组上使用范围,你可以调用' @ user.connections.reject {| c | c.connection_status == ACCEPTED}' – 2010-12-30 19:38:38
或者你可以创建一个连接类方法/作用域'self.with_user(user_id)',它返回'where(“user_id =?”,user_id) '然后链接它们(例如'Connection.with_user(@ user.id).pending')。对于rails 3语法感到抱歉,但是因为我使用了rails 2查询已经有一段时间了 – 2010-12-30 19:43:27