class User < ActiveRecord::Base
has_one :report
has_many :invoices
end
class Report
include ActiveModel::Model
belongs_to :user
def self.monthly_sales
user.invoices.group_by { |i| i.date.beginning_of_month }
end
end
不幸的是,上面的代码无效。我想访问我的报告方法,例如@user.report.monthly_sales
。我觉得我很接近它。请告诉我如何关联这两个模型的方式。
答案 0 :(得分:1)
而不是关联,你可以这样做:
class User < ActiveRecord::Base
has_many :invoices
def report
@report ||= Report.new(self)
@report
end
end
class Report
include ActiveModel::Model
def initialize(user)
@user = user
end
def monthly_sales
user.invoices.group_by { |i| i.date.beginning_of_month }
end
end