turhanco
turhanco

Reputation: 941

How to associate ActiveRecord model and plain class model

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.

Upvotes: 0

Views: 187

Answers (1)

xdazz
xdazz

Reputation: 160833

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

Upvotes: 1

Related Questions