before_add callback using nested_attributes
-
22-07-2019 - |
Question
Given the following:
Foo has_many :bars, :through => :baz
and
Foo accepts_nested_attributes_for :bar
I want to do a find_or_create_by_name
when I add a new :bar
, but I don't know where I can have some sort of before_add
functionality.
The background of this question is Bar validates_uniqueness_of :name
, which gives errors when I try to create a new Foo
that is using an existing Bar
.
Solution
Wow I must be tired:
class Foo < ActiveRecord::Base
has_many :bars, :through => :baz, :before_add => :some_callback
def some_callback(b)
#whatnot
end
end
But still, in the some_callback
portion, what to do? I've tried things like b = Bar.find_or_create_by_name(b.name)
but that doesn't work either.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow