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
你能确认你的数据库中至少有1个Timelog吗?或者发布完整的NoMethodError错误。 –