Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_one :through doesn't provide build_association

A TimeLog can either be Invoiced or not, and an Invoice contains many TimeLogs. Our database can't have nullable foreign keys, so we're using a join model. The code:

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 works fine, but TimeLog.first.build_invoice gives

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

Isn't has_one supposed to make the build_association method available?

Update:

I've made a sample repo for this question: build_assocation_test. To see the problem, clone the repo, install the bundle, run the migrations (or load the schema), and then in a rails console:

Invoice.create
Invoice.first.time_logs.build
TimeLog.create
TimeLog.first.build_invoice
like image 603
Shea Levy Avatar asked Nov 14 '22 16:11

Shea Levy


1 Answers

I believe you have a typo.

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

should be...

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

no?

like image 105
Lester Peabody Avatar answered Jan 21 '23 04:01

Lester Peabody