0

Rails - Best-Practice: How to create dependent has_one relations

Similar to the question above. I have a record that I want to have one (polymorphic relationship), but a "default" dependent object isn't goo enough? The closest I can find is Is it possible to pass params from to a before_create in a model?, but since it has very low upvotes and is clunky I'm not sure it is the "right" solution.

class A < ActiveRecord::Base
  has_one :b, :as=>:foo, :dependent=>:destroy
  accepts_nested_attributes_for :b

end

class B < ActiveRecord::Base
  belongs_to :foo, polymorphic:  true
end
Community
  • 1
  • 1
IdeaHat
  • 7,641
  • 1
  • 22
  • 53
  • I'm not really sure what your question is, but relations are always lower case and if it's has_one and belongs_to, singular. So 'has_one :b' – AJFaraday Sep 16 '14 at 12:43
  • @AJFaraday thanks,I fixed it. It is "right" in my code, this is just standin stuff. Basically, I want to make sure that there is a B for an A. When a.save gets called in the controller, it should make a B in the B table as well. – IdeaHat Sep 16 '14 at 12:48

1 Answers1

0

Typically this will create from accepts_nested_attribute_for, as you've demonstrated, assuming this is passed from your form. You could try a customised validaiton

validate :check_has_b

def check_has_b
  unless b and b.valid?
    errors.add(:base, "You must have a valid B ")
  end
end
AJFaraday
  • 2,411
  • 1
  • 16
  • 39