Skip to content

Instantly share code, notes, and snippets.

@masciugo
Last active August 29, 2015 14:05
Show Gist options
  • Save masciugo/6adc4ddf71e313169bb2 to your computer and use it in GitHub Desktop.
Save masciugo/6adc4ddf71e313169bb2 to your computer and use it in GitHub Desktop.
Associated objects creation failing in a callback
require "rubygems"
require 'active_record'
require "sqlite3"
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "test.sqlite3"
)
ActiveRecord::Migration.class_eval do
drop_table(:posts)
create_table(:posts) do |t|
t.column :title, :string
end
drop_table(:authors)
create_table(:authors) do |t|
t.column :name, :string
t.column :post_id, :integer
end
end
class Post < ActiveRecord::Base
has_one :author
before_save :add_author
def add_author
a = build_author(name: 'default name')
a.valid? # callbacks need to return false to cancel later calbacks and rollback the transaction
end
end
class Author < ActiveRecord::Base
belongs_to :post
# always invalid
validate do |a|
a.errors.add(:base,'bla')
end
end
# Post.delete_all
# Author.delete_all
post=Post.create(title: 'primo post')
p Post.all
p Author.all
@masciugo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment