简体   繁体   中英

Rails associations - NoMethodError: undefined method

Working on project with associations between Invoices and Vat (both models). Every time I try to get a value of the Vat through the console like @Invoice.last.vat.amount I get the message Rails associations - NoMethodError: undefined method

I think I have the migrations done correctly but somehow I'm overlooking something:

My models:

class Vat < ActiveRecord::Base
  belongs_to :invoice
end

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

My migrations:

For Invoices

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

For Vat

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

      t.timestamps
    end
  end
end

And a later modification to add Vat to Invoices :

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

You are almost there, however

1) You set your Invoice has_many vats, means you need to call vats, ie Invoice.last.vats

2) I have not seen amount, but I know count. So you want to do Invoice.last.vats.count .

Enjoy!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM