0
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

Unfortunately the code above is not working. I want to access my report methods like @user.report.monthly_sales. I feel like I am so close to it. Please show me the way how to associate these two models.

turhanco
  • 941
  • 10
  • 19

1 Answers1

1

Instead of association, you could just do like below:

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
xdazz
  • 158,678
  • 38
  • 247
  • 274