Last active
August 29, 2015 14:05
-
-
Save masciugo/6adc4ddf71e313169bb2 to your computer and use it in GitHub Desktop.
Associated objects creation failing in a callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
also consider:
http://www.samuelmullen.com/2013/05/the-problem-with-rails-callbacks/