是否可以构建动态可链接范围?

时间:2017-08-10 13:04:52

标签: ruby-on-rails ruby postgresql ruby-on-rails-4 scope

假设我有这三个模型

% output a vector the same orientation as A
C = A + B.';

% output a vector the same orientation as B
C = A.' + B;

% output a column vector, no matter the orientation of A and B 
% Ensure that they are vectors, this will give undesired results if A and B are 2D.
C = A(:) + B(:);

每个人都有class Plant < ActiveRecord::Base has_many :pots has_many :fertilizers end class Pot < ActiveRecord::Base belongs_to :plant end class Fertilizer < ActiveRecord::Base belongs_to :plant end 的属性。

是否可以制作一个grouped_by范围,可以在以下任何一个结尾处应用:

grouped_as

这样我就可以将@plant.pots.grouped_as('outdoors') @plants.fertilizers.grouped_as('outdoors') 作为可链接范围添加到任何关系中,并且它会自动在grouped_as及其动态子级Plant或{{之间查找公共属性1}} ..

或者我是否必须为每个人制作一个自定义范围?

1 个答案:

答案 0 :(得分:0)

来自http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

我们的想法是使用Association Extensions,然后将它们分离到共享模块。

module FindOrCreateByNameExtension
  def find_or_create_by_name(name)
    first_name, last_name = name.split(" ", 2)
    find_or_create_by(first_name: first_name, last_name: last_name)
  end
end

class Account < ActiveRecord::Base
  has_many :people, extend: FindOrCreateByNameExtension
end

class Company < ActiveRecord::Base
  has_many :people, extend: FindOrCreateByNameExtension
end