2011-10-05 114 views
5

TimeLog既可以开票也可以不开票,而且发票包含许多时间日志。我们的数据库不能有空的外键,所以我们使用了一个连接模型。代码:has_one:通过不提供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给

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

是不是HAS_ONE应该让现有的build_association方法?

更新:

我做了对这个问题的一个样本回购:build_assocation_test。要看到问题,克隆回购,安装包,运行迁移(或加载架构),然后在铁轨控制台:

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

你能确认你的数据库中至少有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并且它可以正常工作 –

+0

我错过了你的错字:)再次检查,对不起。 –

+0

呃,很奇怪,我不知道它有用,只是看起来很奇怪。当我开始工作时,我会检查一下。 –