I think that this is more appropriate for rails-core than the general list.
I’ve been doing a lot of frustrating spelunking in the new ActiveRecord code in Rails 2.1 trying to figure out why our app is not working. Here’s a simplified version of the section of our app which is causing trouble…
We’ve these classes:
class Role << ActiveRecord::Base end
class Membership << ActiveRecord::Base belongs_to :user belongs_to :organization has_many :membership_roles, :dependent => :delete_all has_many :roles, :through => membership_roles
def add_role(role) unless roles(true).include?(role) membership_role = MembershipRole.create!(:membership => self, :role => role) #… end end
class MembershipRole << ActiveRecord::Base belongs_to :membership belongs_to :role validates_uniqueness_of :role_id, :scope => :membership_id end
And there’s this observer
class MembershipObserver < ActiveRecord::Observer def after_create(membership) membership.add_role(Role.find_by_name(“Base”) end end
Now what I’m seeing when I do something like
Membership.create!(:user => some_user, :organization => some_organization)
is that the membership observer’s after_create method gets triggered which calls add_role on the membership which creates the MembershipRole join model, which passes the validates_uniqueness validation.
So far so good,
But then after the observer notifications triggered within the processing of Membership.create!, but before the create! call returns, I’m seeing the validation being run on what looks like an unsaved copy of the MembershipRole which was created in the Membership.add_role method, and this validation fails since the just created MembershipRole with the particular membership and role ids exists in the DB.
This code all worked fine on Rails 2.0.2, something in Rails 2.1 is causing this spurious validation.
I’d welcome any ideas on how to shoot this bug.