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 Fornoles wrote:> On Oct 10, 11:06�am, Alan Sikora
<alansik...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> 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
--
Posted via http://www.ruby-forum.com/.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---