Screencast: Embedded Association

Diese Woche zeigt Ryan Bates in seinem Screencast wie selbstreferenzierende DB-Beziehungen (one-to-many, many-to-many) umgesetzt werden können.

Download (18.7 MB, 14:03)
Alternativer Download für iPod & Apple TV (15.4 MB, 14:03)

Ressourcen:

Quellcode:

One to many:

script/generate migration add_role_to_users role:string
rake db:migrate
# 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
<!-- users/new.html.erb -->
<p>
  <%= f.label :role %><br />
  <%= f.collection_select :role, User::ROLES, :to_s, :titleize %>
</p>

Many to many

script/generate migration add_roles_mask_to_users roles_mask:integer
rake db:migrate
# 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
<!-- 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>

Eingestellt am 23.11.2009 um 16:12

Kategorie: Tutorials

Speichern / Merken / Weitersagen:
  • Print
  • PDF
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • LinkedIn
  • Live
  • MisterWong.DE
  • MisterWong
  • MySpace
  • Netvibes
  • Reddit
  • Technorati
  • Tumblr
  • Webnews.de
  • Yahoo! Bookmarks
  • Yigg
  • Slashdot
  • Twitter
  • Twitthis

Kommentare für diesen Artikel wurden geschlossen.

Suchen auf rubyonrails.de

Aktuelle Rails Version + Abhängigkeiten:

Gem rails-3.0.0
actionmailer (= 3.0.0, runtime)
actionpack (= 3.0.0, runtime)
activerecord (= 3.0.0, runtime)
activeresource (= 3.0.0, runtime)
activesupport (= 3.0.0, runtime)
bundler (~> 1.0.0, runtime)
railties (= 3.0.0, runtime)

Rails auf Rubyforge
Rails auf Github