【问题标题】:Rails associations - NoMethodError: undefined methodRails 关联 - NoMethodError:未定义的方法
【发布时间】:2018-02-20 10:52:23
【问题描述】:

处理与发票和增值税(两种模型)之间的关联的项目。每次我尝试通过 @Invoice.last.vat.amount 之类的控制台获取增值税值时,我都会收到消息 Rails associations - NoMethodError: undefined method

认为我已经正确完成了迁移,但不知何故我忽略了一些东西:

我的模型:

class Vat < ActiveRecord::Base
  belongs_to :invoice
end

class Invoice < ActiveRecord::Base
  has_many :vats
  belongs_to :client
end

我的迁移:

对于发票

class CreateInvoices < ActiveRecord::Migration
  def change
    create_table :invoices do |t|
      t.datetime :issue_time
      t.integer :total
      t.integer :vat
      t.string :item
      t.string :currency
      t.references :client, index: true

      t.timestamps
    end
  end
end

对于增值税

class CreateVats < ActiveRecord::Migration
  def change
    create_table :vats do |t|
      t.integer :amount
      t.string :name

      t.timestamps
    end
  end
end

以及后来的修改,将增值税添加到发票

class AddVatToInvoices < ActiveRecord::Migration
  def change
    add_reference :invoices, :vat, index: true
  end
end

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    不过你快到了

    1) 你设置你的 Invoice has_many vats,意味着你需要调用vats,即Invoice.last.vats

    2) 我没有看到数量,但我知道计数。所以你想做Invoice.last.vats.count

    享受吧!

    【讨论】:

    • 否 - 迁移需要 Vats,复数形式。如果我执行 Invoice.last.vat,我会得到正确的增值税 ID,但不是增值税表中的列的增值税金额。
    • 您确定要金额吗?我可以在我的导轨中看到计数 c。金额抛出错误消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2018-06-16
    • 2015-06-30
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多