Reputation: 315
I am trying to call the user_id
and role_id
field from a hash current_role
. When I try calling current_role.role_id
or current_role.user_id
, I get the following error message:
ActionView::Template::Error (undefined method `role_id' for #<ActiveRecord::Relation::ActiveRecord_Relation_RoleMembership:0x00000103d4fbd0>):
If I try to run current_role.inspect
, I see that both user_id
and role_id
are both set. Here is the response from current_role.inspect
:
#<ActiveRecord::Relation [#<RoleMembership id: 1, user_id: 1, role_id: 2, created_at: "2014-01-27 02:25:25", updated_at: "2014-01-27 02:25:25">]>
Why am I unable to call current_role.role_id
or current_role.user_id
? Any help would be appreciated.
Upvotes: 0
Views: 322
Reputation: 38645
That's because current_role
is an instance of ActiveRecord::Relation
and not RoleMembership
.
To get the role_id
of the first RoleMembership
in the current_role
relation, use:
current_role.first.role_id
If you want to make current_role default to the first RoleMembership
, you should update your current_role
definition to something like follows:
def current_role
RoleMembership.where(...).first
end
With the updated current_role
definition, you will then be able to use current_role.role_id
and it will return the expected role_id
.
Upvotes: 2