【问题标题】:ActiveRecord poly Appended Array vs Concatenated ArrayActiveRecord 多附加数组与级联数组
【发布时间】:2010-12-18 09:26:54
【问题描述】:

当我为以下内容调用@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 方法。

所以我想我的问题归结为......

ActiveRecord 上的“

【问题讨论】:

    标签: ruby-on-rails arrays activerecord


    【解决方案1】:

    模型已更新,因为 left_connections 已使用 &lt;&lt; 方法更新。这使得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 方法,我无法告诉您为什么它们会在没有看到它们的情况下失败。

    【讨论】:

    • 谢谢加勒特。我已经用一些在连接模型中失败的命名范围更新了这个问题。所以剩下的问题是“我如何调用@user.connections.pending?
    • 啊,所以问题是 .connections() 返回一个数组,你不能在数组上使用范围。你可以打电话给@user.connections.reject{ |c| c.connection_status == ACCEPTED }
    • 或者您可以创建一个连接类方法/范围self.with_user(user_id),它返回where("user_id = ?", user_id),然后将它们链接起来(例如Connection.with_user(@user.id).pending)。对不起,rails 3 语法,但我已经有一段时间没有使用 rails 2 查询了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多