# Another "I'm I right" question

**URL:** <https://www.ruby-forum.com/t/another-im-i-right-question/150591>\
**Category:** Rails\
**Created:** [October 10, 2008, 8:49am UTC](https://www.ruby-forum.com/t/another-im-i-right-question/150591 "2008-10-10T08:49:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![apswartz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/71e660/32.png) [@apswartz](https://www.ruby-forum.com/u/apswartz)\
**Post date:** [October 10, 2008, 8:49am UTC](https://www.ruby-forum.com/t/another-im-i-right-question/150591/1 "2008-10-10T08:49:58Z")

</div>

I’m pretty sure that there’s a better way to do this:

@roles = Role.find(:all)  
@selected\_role = Role.find(@user.role\_id)

Can someone help me?

---

<div class="post-metadata">

**Author:** ![apswartz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/71e660/32.png) [@apswartz](https://www.ruby-forum.com/u/apswartz)\
**Post date:** [October 10, 2008, 9:01am UTC](https://www.ruby-forum.com/t/another-im-i-right-question/150591/2 "2008-10-10T09:01:05Z")

</div>

On Oct 10, 11:06 am, Alan S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I’m pretty sure that there’s a better way to do this:
> 
> @roles = Role.find(:all)  
> @selected\_role = Role.find(@user.role\_id)
> 
> Can someone help me?

Why not just (assuming user is associated to role):

@selected\_role = @user.role

---

<div class="post-metadata">

**Author:** ![apswartz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/71e660/32.png) [@apswartz](https://www.ruby-forum.com/u/apswartz)\
**Post date:** [October 10, 2008, 9:24pm UTC](https://www.ruby-forum.com/t/another-im-i-right-question/150591/3 "2008-10-10T21:24:04Z")

</div>

Since this is the second question like this, with essentially the same  
answer I’m going to flesh out the answer a little further.

If you have a schema like this:

roles  
t.integer :id  
t.string :name

users  
t.integer :id  
t.string :first\_name  
t.string :last\_name  
t.integer :role\_id

And models like this:

class Role \< ActiveRecord::Base  
has\_many :users  
end

class User \< ActiveRecord::Base  
belongs\_to :role  
end

Then you can do stuff like this:

role = Role.find\_by\_name(“Administrators”) # Get the role named  
“Administrators”  
users = role.users # Get all the users in the role  
user = role.users.find(:first, :order =\> :last\_name) # Find the first  
user in the role ordered by last name  
user.role.name # Get the name of the role of the user

Erol F. wrote:

> On Oct 10, 11:06ï¿½am, Alan S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:
> 
> > I’m pretty sure that there’s a better way to do this:
> > 
> > @roles = Role.find(:all)  
> > @selected\_role = Role.find(@user.role\_id)
> > 
> > Can someone help me?
> 
> Why not just (assuming user is associated to role):
> 
> @selected\_role = @user.role
