about 4 years ago

Rails Delegate是ActiveSupport內的Delegate module
它可以讓一個class直接取用另外一個關聯class的attribute
例如Rails專案中有時會看到這樣的設定:

model.post.rb
=begin
Schema Information
Table name: users
  id                     :integer          not null, primary key
  title                   :string(255)
  created_at             :datetime
  updated_at             :datetime
=end
class Post
  belongs_to :user
  delegate :name, :to => :user, :allow_nil => true
end
model/user.rb
=begin
Schema Information
Table name: users
  id                     :integer          not null, primary key
  name                   :string(255)
  created_at             :datetime
  updated_at             :datetime
=end
class User
  has_many :posts
end

在這裏Post下了delegate指令的意思就是讓@post.name可以回傳@post.user.name的值,:allow_nil的目的是讓name的值為nil時不會噴錯。
另外delegate也有一些好用的選項可以使用,例如prefix可以讓剛剛的post輸出方式變成@post.user_name

class Post
  belongs_to :user
  delegate :name, :to => :user, :prefix => true, :allow_nil => true
end

或是可以自定prefix,例如下方例子就會變成@post.owner_name

class Post
  belongs_to :user
  delegate :name, :to => :user, :prefix => "owner", :allow_nil => true
end

參考文章

← Rails讓網址不再只顯示ID Nested Attributes with Strong Parameters →
 
comments powered by Disqus