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