has_one:through不提供build_association

时间:2011-10-05 19:30:05

标签: ruby-on-rails-3

TimeLog可以是开票还是不开票,而发票包含许多TimeLog。我们的数据库不能有可空的外键,所以我们使用的是连接模型。代码:

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'for   #&LT; TimeLog:0x4acd588&GT;

是不是has_one应该使build_association方法可用?

更新

我为这个问题制作了一个样本回购:build_assocation_test。要查看问题,请克隆存储库,安装捆绑包,运行迁移(或加载架构),然后在rails控制台中:

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

1 个答案:

答案 0 :(得分: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

没有