On creation of a record, I am attempting, on creation of parent class Quote, to set default values for related class Optionvolume
class Optionvolume < ActiveRecord::Base
belongs_to :option
belongs_to :quote
class Option < ActiveRecord::Base
has_and_belongs_to_many :tasks
class Task < ActiveRecord::Base
has_and_belongs_to_many :options
class Quote < ActiveRecord::Base
belongs_to :task
has_many :optionvolumes, :dependent => :destroy
has_many :options, through: :optionvolumes
accepts_nested_attributes_for :optionvolumes, :allow_destroy => true
after_create :set_optionvolumes
private
def set_optionvolumes
@options = Option.where(['options_tasks.task_id = ?', self.task_id]).joins(:tasks)
@options.each do |option|
self.optionvolumes.create(:quantity => '0', :option_id => option.id)
end
end
However, I am generating the records partially. While the @options generates, for the given case 10 results (correctly). However, only the the quantity field is being generated (as is the quote_id rails handles via the context). the option_id remains blank
Optionvolume id: 111, quote_id: 27, quantity: 0, created_at: [...]
Optionvolume id: 112, quote_id: 27, quantity: 0, created_at: [...]
etc...
The server is even indicating that it should be handling the data
INSERT INTO "optionvolumes" ("option_id", "quote_id", "created_at", "quantity", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["option_id", 15], ["quote_id", 38], ["created_at", Tue, 13 Aug 2013 11:20:07 UTC +00:00], ["quantity", 0], ["updated_at", Tue, 13 Aug 2013 11:20:07 UTC +00:00]]
INSERT INTO "optionvolumes" ("option_id", "quote_id", "created_at", "quantity", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["option_id", 16], ["quote_id", 38], ["created_at", Tue, 13 Aug 2013 11:20:07 UTC +00:00], ["quantity", 0], ["updated_at", Tue, 13 Aug 2013 11:20:07 UTC +00:00]]
etc...
It turns out the server log is simply not showing the option_id being saved, but the application is handling it. A
command shows it's there. http://guides.rubyonrails.org/debugging_rails_applications.html was quite helpful in this regard.