当前位置: 动力学知识库 > 问答 > 编程问答 >

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, i.e. Invoice.last.vats

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

Enjoy!

分享给朋友:
您可能感兴趣的文章:
随机阅读: