一个TimeLog可以被开具发票,也可以不被开具发票,并且一个发票包含许多TimeLogs。我们的数据库不能有可为空的外键,因此我们使用的是联接模型。代码:
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:未定义的方法“ build_invoice”
#
has_one是否不应该使build_association方法可用?
更新:
我为这个问题做了一个样本回购:build_assocation_test。要查看问题,请克隆存储库,安装捆绑软件,运行迁移(或加载架构),然后在rails控制台中:
Invoice.create
Invoice.first.time_logs.build
TimeLog.create
TimeLog.first.build_invoice
最佳答案
我相信你有错字。
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
没有?