Polymorphic and standard association issue

Hello all,

I'm having a strange issue with a model that belongs_to two other models. The one association is polymorphic and the other is normal.

I'm sorry to anyone who has spent any time on this at all. I hope since I found the problem so quickly after posting this no one has.

The issue was that I was attempting to find all roles for the currently logged in user. While they are creating a new User.

Basically @user was set in the controller as User.new and I needed to call current_user.roles instead.

Thank you listening to me and sorry again

No prob. I was looking into it and was going to suggest this version:

@user = User.find(1)

new_role = @user.roles.create({:role => 100})

Just a little bit neater (no need for the Role.create and for the “dirty” pointer to the user_id) …

or even better (IMHO)

class User < ActiveRecord::Base

has_many :roles, :inverse_of :user

@user = User.find(1)

new_role = @user.roles.build({:role => 100}) new_role. … = …

do all you have to do in memory and finish it off with

if user.save

OK

else

handle the problem

end

Which will give you a nice transaction over all. So, if it only partially succeeds, you have an all or nothing to you database.

(0.2ms) BEGIN SQL (0.5ms) INSERT INTO …

SQL (0.4ms) INSERT INTO … (13.1ms) COMMIT

With the inverse_of, also the belongs_to is automatically filled in.

HTH,

Peter