# Validations not working on complex DB transaction

**URL:** <https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052>\
**Category:** Rails\
**Created:** [August 1, 2013, 4:56pm UTC](https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052 "2013-08-01T16:56:06Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![alcina](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a587f6/32.png) [@alcina](https://www.ruby-forum.com/u/alcina)\
**Post date:** [August 1, 2013, 4:56pm UTC](https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052/1 "2013-08-01T16:56:06Z")

</div>

The models:

class User  
has\_many :institution\_memberships  
belongs\_to :account

```
after_create :set_default_membership

def set_default_membership
    if institution_memberships.empty?
      institution_memberships.create(default_data_from_account)
    end
end

```

end

class InstitutionMembership  
validates\_uniqueness\_of :user\_id, :scope =\> :institution\_id  
end

Controller:

def create  
@account = Account.new  
@account.transaction do  
@user = User.new(params[:user])  
@institution = Institution.new(:name =\> @account.name)  
@user.account = @account  
@institution.account = @account  
@institution\_membership = InstitutionMembership.new(  
:institution =\> @institution,  
:user =\> @user  
)

```
    if @user.save && @institution.save &&

```

@institution\_membership.save

```
    end
end

```

end

To put this into context. A user can belong to one or many institutions.  
The relationship is managed through :institution\_memberships. A user can  
only have one membership per institution, hence the  
validates\_uniqueness\_of :user\_id, :scope =\> :institution\_id

There is a lot more code happening around all of this than i’ve shown,  
but the main problem is that basically two memberships are being created  
for a user with the same institution. The validate is not working. The  
after\_create callback is creating an object successfully, and the  
standard save in the controller is working.

My guess is it has something to do with the timing of things and when  
they’re actually written to the database, but i don’t know that process  
well enough to pinpoint the exact cause. Obviously there is no need to  
create a membership object in the controller, but the code had been that  
way for a long time without a problem. Nobody noticed it until suddenly  
the bad data started showing up. I’m more curious as to why the  
validation goes through.

What’s the community think?

---

<div class="post-metadata">

**Author:** ![mastabog](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/df705f/32.png) [@mastabog](https://www.ruby-forum.com/u/mastabog)\
**Post date:** [August 2, 2013, 6:18pm UTC](https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052/2 "2013-08-02T18:18:10Z")

</div>

On Thursday, 1 August 2013 10:56:06 UTC-4, [Ruby-Forum.com](http://Ruby-Forum.com) User wrote:

> ```
> if institution_memberships.empty?
> 
> )
> 
> ```
> 
> only have one membership per institution, hence the  
> well enough to pinpoint the exact cause. Obviously there is no need to  
> create a membership object in the controller, but the code had been that  
> way for a long time without a problem. Nobody noticed it until suddenly  
> the bad data started showing up. I’m more curious as to why the  
> validation goes through.
> 
> What’s the community think?

Can you post a log of the SQL that gets executed during the transaction?  
I’m curious about what the validates\_uniqueness\_of is looking up, if  
anything.

–Matt J.

---

<div class="post-metadata">

**Author:** ![mastabog](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/df705f/32.png) [@mastabog](https://www.ruby-forum.com/u/mastabog)\
**Post date:** [August 6, 2013, 11:22am UTC](https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052/3 "2013-08-06T11:22:11Z")

</div>

Hi,

The @user object is getting saved first. That time, there is no  
instuition membership attached to it. So one is getting created. Then  
when you save the instuition membership again inside the controller it  
also gets saved.

Is this clear?

On Sat, Aug 3, 2013 at 2:00 AM, masta Blasta [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> > > validation goes through.
> 
> –  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).
> 
> –  
> You received this message because you are subscribed to the Google G. “Ruby  
> on Rails: Talk” group.  
> To unsubscribe from this group and stop receiving emails from it, send an email  
> to [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid).  
> To post to this group, send email to [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid).  
> To view this discussion on the web visit  
> [https://groups.google.com/d/msgid/rubyonrails-talk/6980a8a3360434ff72301fbf698f61c2%40ruby-forum.com](https://groups.google.com/d/msgid/rubyonrails-talk/6980a8a3360434ff72301fbf698f61c2%40ruby-forum.com).  
> For more options, visit [https://groups.google.com/groups/opt\_out](https://groups.google.com/groups/opt_out).

–  
Azhagu Selvan

[http://tamizhgeek.in](http://tamizhgeek.in)

---

<div class="post-metadata">

**Author:** ![mastabog](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/df705f/32.png) [@mastabog](https://www.ruby-forum.com/u/mastabog)\
**Post date:** [August 6, 2013, 1:21pm UTC](https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052/4 "2013-08-06T13:21:57Z")

</div>

Yeah, It’s exactly that… you are creating a user before the  
Institution…  
But I your controller isn’t searching for some Institution while  
creating  
the User… I just see your controller creating an Institution…  
doesn’t  
matter if already exists…

_Carlos Figueiredo_

---

<div class="post-metadata">

**Author:** ![mastabog](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/df705f/32.png) [@mastabog](https://www.ruby-forum.com/u/mastabog)\
**Post date:** [August 2, 2013, 10:30pm UTC](https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052/5 "2013-08-02T22:30:23Z")

</div>

Matt J. wrote in post #1117517:

> On Thursday, 1 August 2013 10:56:06 UTC-4, [Ruby-Forum.com](http://Ruby-Forum.com) User wrote:
> 
> > ```
> > if institution_memberships.empty?
> > 
> > )
> > 
> > ```
> > 
> > only have one membership per institution, hence the  
> > well enough to pinpoint the exact cause. Obviously there is no need to  
> > create a membership object in the controller, but the code had been that  
> > way for a long time without a problem. Nobody noticed it until suddenly  
> > the bad data started showing up. I’m more curious as to why the  
> > validation goes through.
> > 
> > What’s the community think?
> 
> Can you post a log of the SQL that gets executed during the transaction?  
> I’m curious about what the validates\_uniqueness\_of is looking up, if  
> anything.
> 
> –Matt J.

I attached a part of the log from my functional testing. What i assume  
to be the validation check SELECT statement does not have a user\_id yet.  
However the DB INSERT occurring right after, does have the user\_id.

Very puzzling. FYI I’m on Rails 2.3.15

---

<div class="post-metadata">

**Author:** ![mastabog](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/df705f/32.png) [@mastabog](https://www.ruby-forum.com/u/mastabog)\
**Post date:** [August 6, 2013, 4:13pm UTC](https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052/6 "2013-08-06T16:13:47Z")

</div>

[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote in post #1117870:

> Hi,
> 
> The @user object is getting saved first. That time, there is no  
> instuition membership attached to it. So one is getting created. Then  
> when you save the instuition membership again inside the controller it  
> also gets saved.
> 
> Is this clear?

You just restated what i had initially written.

The “problem” is something to do with how rails connects newly  
initialized objects that are in memory but not yet in the database.

We have built two objects like this  
u = User.new  
im = InstitutionMembership.new :user =\> u

At that point the u (User) object doesn’t know anything about the im  
object. Saving the u object does not trigger an autosave on the  
association, and the create callback creates a new membership. That’s  
somewhat expected.

The odd issues appear after -  
u = User.new  
im = InstitutionMembership.new :user =\> u  
u.save  
im.save

‘im’ is aware of the user object, however it is not able to validate  
against it. When it attempts to validate, the user\_id==NULL. At the very  
next log entry though, it saves itself with the correct user\_id. So  
somewhere between the validate callbacks, and the create and commit  
callbacks, the ‘im’ object refreshed the user object and retrieved the  
user\_id. Also the new\_record? flag on ‘im’ is still set, so a new row is  
created.

One of the better solutions was actually to do:  
u = User.new  
im = u.institution\_memberships.build

This is able to properly connect the objects in memory, and the process  
works smoothly. The association is autosaved on u.save

---

<div class="post-metadata">

**Author:** ![mastabog](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/df705f/32.png) [@mastabog](https://www.ruby-forum.com/u/mastabog)\
**Post date:** [August 6, 2013, 4:46pm UTC](https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052/7 "2013-08-06T16:46:23Z")

</div>

On 2013-Aug-6, at 10:13 , masta Blasta wrote:

> You just restated what i had initially written.  
> object. Saving the u object does not trigger an autosave on the  
> association, and the create callback creates a new membership. That’s  
> somewhat expected.

So tell ActiveRecord that you _want_ the autosave:

class User \< ActiveRecord::Base  
belongs\_to :account  
has\_many :institution\_memberships, :autosave =\> :always  
has\_many :institutions, :through =\> :institution\_memberships

after\_create :set\_default\_membership

def set\_default\_membership  
if institution\_memberships(true).blank?  
institution\_memberships.create(default\_data\_from\_account)  
end  
end  
end

class InstitutionMembership \< ActiveRecord::Base  
belongs\_to :user  
belongs\_to :institution  
validates\_uniqueness\_of :user\_id, :scope =\> :institution\_id  
end

Note the argument to ‘institution\_memberships(true)’ which causes the  
memberships to be reloaded from the database.

> The odd issues appear after -  
> u = User.new  
> im = InstitutionMembership.new :user =\> u  
> u.save  
> im.save

I assume that you’ve simplified this so that the account\_id or however  
the default\_data\_from\_account manages to find the institution\_id is  
missing.

u = User.new  
u.institutions \<\< Institution.find(somehow)

or

u = User.new  
u.institution\_memberships \<\< InstitutionMembership.new(:institution\_id  
=\> from\_a\_parameter\_perhaps)

and then the u.save should do the right thing.

-Rob

---

<div class="post-metadata">

**Author:** ![mastabog](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/df705f/32.png) [@mastabog](https://www.ruby-forum.com/u/mastabog)\
**Post date:** [August 6, 2013, 4:48pm UTC](https://www.ruby-forum.com/t/validations-not-working-on-complex-db-transaction/236052/8 "2013-08-06T16:48:08Z")

</div>

On 2013-Aug-6, at 10:13 , masta Blasta wrote:

> You just restated what i had initially written.  
> object. Saving the u object does not trigger an autosave on the  
> association, and the create callback creates a new membership. That’s  
> somewhat expected.

So tell ActiveRecord that you _want_ the autosave:

class User \< ActiveRecord::Base  
belongs\_to :account  
has\_many :institution\_memberships, :autosave =\> :always  
has\_many :institutions, :through =\> :institution\_memberships

after\_create :set\_default\_membership

def set\_default\_membership  
if institution\_memberships(true).blank?  
institution\_memberships.create(default\_data\_from\_account)  
end  
end  
end

class InstitutionMembership \< ActiveRecord::Base  
belongs\_to :user  
belongs\_to :institution  
validates\_uniqueness\_of :user\_id, :scope =\> :institution\_id  
end

Note the argument to ‘institution\_memberships(true)’ which causes the  
memberships to be reloaded from the database and the :autosave option  
added to the has\_many.

> The odd issues appear after -  
> u = User.new  
> im = InstitutionMembership.new :user =\> u  
> u.save  
> im.save

I assume that you’ve simplified this so that the account\_id or however  
the default\_data\_from\_account manages to find the institution\_id is  
missing.

u = User.new  
u.institutions \<\< Institution.find(somehow)

or

u = User.new  
u.institution\_memberships \<\< InstitutionMembership.new(:institution\_id  
=\> from\_a\_parameter\_perhaps)

and then the u.save should do the right thing.

-Rob
