LoginSignup
5
6

More than 5 years have passed since last update.

Rails Best Practices | the Law of Demeter

Posted at

Rails Best Practices | the Law of Demeter

delegate設定

app/models/item.rb

  belongs_to :user

  delegate :name, to: :user, prefix: true, allow_nil: true

userが存在しないitem

Item.first.user.tapp
  Item Load (0.3ms)  SELECT "items".* FROM "items" LIMIT 1
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 0 LIMIT 1
nil
=> nil

delegateを介してuser.nameを呼ぶ

Item.first.user_name.tapp
  Item Load (0.4ms)  SELECT "items".* FROM "items" LIMIT 1
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 0 LIMIT 1
nil
=> nil

delegateを介さずにuser.nameを呼ぶ

Item.first.user.name.tapp
  Item Load (0.1ms)  SELECT "items".* FROM "items" LIMIT 1
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 0 LIMIT 1
NoMethodError: undefined method `name' for nil:NilClass
    from (irb):149
    from /Users/shu/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/railties-3.2.12/lib/rails/commands/console.rb:47:in `start'
    from /Users/shu/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/railties-3.2.12/lib/rails/commands/console.rb:8:in `start'
    from /Users/shu/.rbenv/versions/2.0.0-p0/lib/ruby/gems/2.0.0/gems/railties-3.2.12/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'
5
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6