2011-10-05 22 views
5

TimeLogは請求書にすることができますが、Invoiceには多くのTimeLogが含まれます。私たちのデータベースにはヌル可能な外部キーはありません。そのため、結合モデルを使用しています。コード:has_one:throughはbuild_associationを提供しません

class TimeLog < ActiveRecord::Base 
    has_one :invoices_time_logs 
    has_one :invoice, through: :invoices_time_logs 
end 

class Invoice < ActiveRecord::Base 
    has_many :invoices_time_logss 
    has_many :time_logs, through: :invoices_time_logss 
end 

class InvoicesTimeLogs 
    belongs_to :invoice 
    belongs_to :time_log 
end 

Invoice.first.time_logs.buildが正常に動作しますが、TimeLog.first.build_invoiceはbuild_associationメソッドを利用できるようになってhas_oneのではないです

NoMethodError: undefined method `build_invoice' for #<TimeLog:0x4acd588>

を与えますか?

更新:build_assocation_test

私はこの質問のためのサンプルのレポを作りました。 、問題を参照してくださいレポのクローンを作成し、バンドルをインストールし、移行を実行します(またはスキーマをロード)した後、レールコンソールにするには、次の

Invoice.create 
Invoice.first.time_logs.build 
TimeLog.create 
TimeLog.first.build_invoice 
+0

DBに1つ以上のTimelogがあることを確認できますか?または、完全なNoMethodErrorエラーを送信します。 –

答えて

1

私はあなたがタイプミスを持っていると信じています。

class Invoice < ActiveRecord::Base 
    has_many :invoices_time_logss 
    has_many :time_logs, through: :invoices_time_logss 
end 

はありません...

class Invoice < ActiveRecord::Base 
    has_many :invoices_time_logs 
    has_many :time_logs, through: :invoices_time_logs 
end 

すべきですか?

+0

私はそれらの違いは見当たりません。 Invoice.time_logs.buildを実行して正常に動作するので、私のInvoiceクラスが正しく設定されていることを確信しています。 –

+0

私はあなたのタイプミスをタイプミットしました。 –

+0

ええ、変わった、私はおそらくそれは動作しない、ちょうど私に奇妙に見えます。私が少しでも仕事をしたら、それをチェックします。 –

関連する問題