Download (18.7 MB, 14:03)
Alternativer Download für iPod & Apple TV (15.4 MB, 14:03)
Ressourcen:
Quellcode:
One to many:
[bash]
script/generate migration add_role_to_users role:string
rake db:migrate
[/bash]
[ruby]
# models/user.rb
class User < ActiveRecord::Base
acts_as_authentic
has_many :articles
has_many :comments
ROLES = %w[admin moderator author]
def role_symbols
[role.to_sym]
end
end
[/ruby]
[ror]
<!– users/new.html.erb –>
<p>
<%= f.label :role %><br />
<%= f.collection_select :role, User::ROLES, :to_s, :titleize %>
</p>
[/ror]
Many to many
[bash]
script/generate migration add_roles_mask_to_users roles_mask:integer
rake db:migrate
[/bash]
[ruby]
# models/user.rb
class User < ActiveRecord::Base
acts_as_authentic
has_many :articles
has_many :comments
named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0"} }
ROLES = %w[admin moderator author]
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def roles
ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }
end
def role_symbols
roles.map(&:to_sym)
end
end
[/ruby]
[ror]
<!– users/new.html.erb –>
<p>
<%= f.label :roles %><br />
<% for role in User::ROLES %>
<%= check_box_tag "user[roles][]", role, @user.roles.include?(role) %>
<%=h role.humanize %><br />
<% end %>
<%= hidden_field_tag "user[roles][]", "" %>
</p>
[/ror]