Another "I'm I right" question

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?

On Oct 10, 11:06 am, Alan S. [email protected] 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

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. [email protected] 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