Rails:来自祖父母的简单形式关联 label_method

Rails: Simple Form Association label_method from Grandparent

我正在尝试构建一个将使用简单表单创建新记录的表单,但我无法在下拉列表中显示正确的标签。一、相关机型:

class Service < ActiveRecord::Base
  belongs_to :business
  has_one :enrollment
  has_many :clients, through: :enrollment
end

class Client < ActiveRecord::Base
  belongs_to :business
  has_one :enrollment
  has_many :services, through: :enrollment
end

class Enrollment < ActiveRecord::Base
  belongs_to :service
  belongs_to :client
  has_many :jobs
end

class Job < ActiveRecord::Base
  belongs_to :enrollment
end

基本思想是客户将注册一项或多项服务。工作代表执行服务的约会。创建新工作时,我需要 select 该工作所属的注册。来自 html.erb:

<%= f.association :enrollment, label_method: :service_id, value_method: :id, prompt: 'Choose an enrolled service' %>

这类作品,但它只向我展示了来自注册 table 的 service_id。我想看到的是下拉列表中连接的客户端名称(fname 和 lname)和服务名称,如下所示:"John Doe: Window Washing"。问题是这两个都来自 parents 的注册人数。基本上我需要遍历两个关联才能找到我想要的标签。

我想 de-normalizing 让注册记录有我需要的数据,但我不想那样做。

有什么想法吗?

在注册 class 中定义以下方法:

def name
  "#{client.full_name}: #{service.name}"
end

那么你应该可以在你的表单中使用这个方法:

<%= f.association :enrollment, label_method: :name, value_method: :id, prompt: 'Choose an enrolled service' %>

为避免 2*n+1 sql 次查询准备包含客户端和服务的注册集合。