Thursday, April 21, 2011

before_add callback using nested_attributes

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.

From stackoverflow
  • 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, have you resolved your problem?

    i'm here with the same problem.

0 comments:

Post a Comment