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.

================================
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :permission, :polymorphic => true
end

class User < ActiveRecord::Base
has_many :roles
has_many :programs, :through => :roles
end

class Program < ActiveRecord::Base
has_many :roles, :as => :permissions
has_many :users, :through => :roles
end

But for some reason…

================================
@user = User.find(1)
@user.roles << Role.create({:role => 100, :user_id => @user.id})
Rails.logger.info @user.roles.inspect

…returns nothing. I’m very confused here.

My roles table has

| id | user_id | permission_id | permission_type |

| 1 | 1 | NULL | NULL |

If anyone can help me out I’d greatly appreciate it.

Environment:

Ruby: REE
Rails: 3.1.2
Passenger

Thank you,
Sparkmasterflex

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

On Wed, Jan 18, 2012 at 6:53 PM, Keith R. [email protected]
wrote:

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.

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 http://user.id/})
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