Forum: Ruby on Rails Another "I'm I right" question...

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Alan S. (Guest)
on 2008-10-10 10:49
(Received via mailing list)
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?
Erol F. (Guest)
on 2008-10-10 11:01
(Received via mailing list)
On Oct 10, 11:06 am, Alan S. <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
Robert W. (Guest)
on 2008-10-10 23:24
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> 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
This topic is locked and can not be replied to.