RAILS插件delegate_belongs_to

iwa*_*wan 3 plugins ruby-on-rails

有人可以在rails中提供有关此插件delegate_belongs_to的参考和示例吗?

谢谢

小智 11

delegate_belongs_to似乎已被pahanix的delegates_attributes_to取代,但基本思路如下.

假设您Office的Rails应用程序中有一个具有address字段的Employee模型,并且您还有一个属于办公室的模型:

class Office < AcitveRecord::Base
end

class Employee < ActiveRecord::Base
  belongs_to :office
end
Run Code Online (Sandbox Code Playgroud)

如果您想查找员工的地址,您必须执行以下操作:

>> emp.office.address
=> "Edinburgh"
Run Code Online (Sandbox Code Playgroud)

但是,如果你这样使用过delegate_belongs_to:

class Employee < ActiveRecord::Base
  belongs_to :office
  delegate_belongs_to :office
end
Run Code Online (Sandbox Code Playgroud)

您可以直接访问Office模型的属性:

>> emp.address
=> "Edinburgh"
Run Code Online (Sandbox Code Playgroud)

GitHub的页面详细介绍了一些使用插件的其他方式,是值得一读.原始插件似乎已经存在于faber的github页面中.