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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With