Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为关联对象创建方法_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails 为关联对象创建方法

Ruby on rails 为关联对象创建方法,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我有两种型号: class User < ActiveRecord::Base has_many :accounts end class Account < ActiveRecord::Base belongs_to :user end 现在我可以使用User.accounts.filtered(Account::FILTER\u ACTIVE).sorted。我想这是因为scope.class返回ActiveRecord::Relation和User.first.a

我有两种型号:

class User < ActiveRecord::Base
   has_many :accounts
end

class Account < ActiveRecord::Base
   belongs_to :user
end
现在我可以使用
User.accounts.filtered(Account::FILTER\u ACTIVE).sorted
。我想这是因为
scope.class
返回
ActiveRecord::Relation
User.first.accounts.class
返回
Array

我也试过这个:

scope :sorted, lambda { |object|
  object.partition { |account| account.is_referral?}.each do |a| 
    a.sort! {|a,b| a.label <=> b.label}
  end.flatten
}
scope:sorted,lambda{124;对象|
object.partition{| account | account.is|u reference?}。每个都做| a |
a、 排序!{a,b{a.label b.label}
结束。变平
}
但是这会为
nil.partition
抛出
nomethoderor


非常感谢您的帮助。

您可以通过以下操作在关联上定义代理方法

class User < ActiveRecord::Base
  has_many :accounts do
    def sorted
      proxy_target.partition { |account| account.is_referral?}.each do |a| 
           a.sort! {|a,b| a.label <=> b.label}
      end.flatten
    end
  end
end
class用户


将其用于
User.last.accounts(true).sorted
以获得结果,因为否则您的关联将不会加载,并且您将收到空数组。

感谢您的想法,但是我得到的结果是空数组。确切的关系是,
有很多:帐户,:到=>:日历
,但无论我在哪里定义你的方法(在
日历
用户
),我都会得到一个空数组。我发现了为什么我会得到这个结果,并在你的帖子中添加了解释。再次感谢。
scope :sorted, lambda { |object|
  object.partition { |account| account.is_referral?}.each do |a| 
    a.sort! {|a,b| a.label <=> b.label}
  end.flatten
}
class User < ActiveRecord::Base
  has_many :accounts do
    def sorted
      proxy_target.partition { |account| account.is_referral?}.each do |a| 
           a.sort! {|a,b| a.label <=> b.label}
      end.flatten
    end
  end
end