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