views:

260

answers:

2

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.

A: 

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.

Tom Clark
A: 

tom, have you resolved your problem?

i'm here with the same problem.

Guilherme