Created
July 2, 2014 16:57
-
-
Save werner/1b707d875f1638fc44ab to your computer and use it in GitHub Desktop.
Habtm and before create callback
This file contains 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
unless File.exist?('Gemfile') | |
File.write('Gemfile', <<-GEMFILE) | |
source 'https://rubygems.org' | |
gem 'rails', github: 'rails/rails' | |
gem 'arel', github: 'rails/arel' | |
gem 'sqlite3' | |
GEMFILE | |
system 'bundle' | |
end | |
require 'bundler' | |
Bundler.setup(:default) | |
require 'active_record' | |
require 'minitest/autorun' | |
require 'logger' | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :posts do |t| | |
end | |
create_table :comments do |t| | |
t.integer :post_id | |
t.boolean :commented | |
end | |
create_table :comments_posts, id: false do |t| | |
t.references :post, null: false | |
t.references :comment, null: false | |
end | |
end | |
class Post < ActiveRecord::Base | |
has_and_belongs_to_many :comments | |
before_create do | |
if comments.to_a.count < 2 | |
errors.add(:base, "You shoud have at least 2 comments") | |
false | |
end | |
end | |
after_create do | |
comments.update_all(commented: true) | |
end | |
end | |
class Comment < ActiveRecord::Base | |
has_and_belongs_to_many :posts | |
end | |
class BugTest < Minitest::Test | |
def test_association_stuff | |
post = Post.new | |
first_comment = Comment.create! commented: false | |
second_comment = Comment.create! commented: false | |
post.comment_ids = [first_comment.id, second_comment.id] | |
post.save! | |
assert_equal 2, post.comments.count | |
assert_equal 2, Comment.count | |
assert_equal 2, post.comments.where(commented: true).count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment