On Thursday, 1 August 2013 10:56:06 UTC-4, Ruby-Forum.com User wrote:
>
> 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? 
>
>
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 Jones 

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/f3b6e39a-ec5d-47cf-ba8e-805fd0987b0b%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to