· 1 min read

Screencast: Embedded Association

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]

<%= f.label :role %>
<%= f.collection_select :role, User::ROLES, :to_s, :titleize %>

[/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]

<%= f.label :roles %>
<% for role in User::ROLES %> <%= check_box_tag “user[roles][]”, role, @user.roles.include?(role) %> <%=h role.humanize %>
<% end %> <%= hidden_field_tag “user[roles][]”, "" %>

[/ror]

Back to Blog