检索多态,has_one和作用域关联的方法

时间:2015-10-21 23:27:20

标签: ruby-on-rails-4 scope polymorphic-associations has-one helpermethods

嗨,这有点琐碎,但我不能为我的生活找出在哪里进行调整。 我有一个LoanApplication模型和这样的传输模型:

class LoanApplication < ActiveRecord::Base
  before_save :populate_guid
  belongs_to :user
  has_one :loan, -> { where loan: true }, as: :transferable
  has_one :repayment, -> { where repayment: true }, as: :transferable
  validates_uniqueness_of :guid  

  private 

  def populate_guid
    if new_record?
      while !valid? || self.guid.nil?
        self.guid = SecureRandom.random_number(1_000_000_000).to_s(36)
      end
    end
  end
end

class Transfer < ActiveRecord::Base
  belongs_to :transferable, polymorphic: true 
  belongs_to :user
 validates_presence_of :transferable_id,
                    :transferable_type,
                    :user_id,
                    :amount,
                    :password
end

为什么LoanApplication.first.loan会给我以下错误消息

LoanApplication Load (1.1ms)  SELECT  "loan_applications".* FROM "loan_applications"  ORDER BY "loan_applications"."id" ASC LIMIT 1
NameError: uninitialized constant LoanApplication::Loan

所有见解都表示赞赏。 感谢

2 个答案:

答案 0 :(得分:0)

我认为应用程序是一个保留字。尝试重命名LoanApplication?

答案 1 :(得分:0)

这很简单,我只需要添加class_name: "Transfer"即可。 -__-'