【问题标题】:How to associate ActiveRecord model and plain class model如何关联 ActiveRecord 模型和普通类模型
【发布时间】:2014-12-26 01:17:10
【问题描述】:
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。我觉得我离它很近。请告诉我如何关联这两个模型。

【问题讨论】:

    标签: ruby-on-rails activerecord activemodel


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多