質問

Take the following for example:

class Foo < AR::Base
  has_many :bars, :as => :barable, :dependent=> :destroy
  accepts_nested_attributes_for :bars, :allow_destroy => true
end

class Bar < AR::Base
   belongs_to :barable, :polymorphic => true  
end

class Baz < Bar

  before_save do 
    raise "Hi"
  end

end

In the form for 'Foo' - I have fields_for :bars_attributes where a hidden field sets type to 'Baz'. The 'Baz' is succesfully created but the callback never fires. (It does, however, fire when manually creating a 'Baz' in the console.)

Any advice appreciated!

役に立ちましたか?

解決

Baz's callbacks will only be triggered if you create it as a Baz object, i.e Baz.new(...).

However, you're not creating a Baz record, but rather a Bar record: Bar.new(type: 'Baz'). This will only trigger Bar's callbacks, even though that later on it will be treated as a Baz.

他のヒント

you need to specify additonal association in your Foo.rb

has_many :bazs
# or
# has_many :bazs class_name: 'ModuleName::Baz' # if you scoped your child classed within some module

If you do that your

before_save do 
  raise "Hi"
end

will fire on for example @current_user.bazs.build

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top