Rails:来自Grandparent的简单表单关联label_method



我正在尝试构建一个表单,该表单将使用Simple form创建一个新记录,但在下拉列表中显示正确的标签时遇到了问题。首先,相关模型:

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

其基本思想是,客户端将注册一个或多个服务。作业表示执行服务的预约。创建新作业时,我需要选择该作业所属的注册。从html.erb:

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

这种方法是有效的,但它只显示Enrollment表中的service_id。我想看到的是连接在下拉列表中的客户端名称(fname和lname)和服务名称,如下所示:"John Doe:Window Washing"。问题是,这两个都来自Enrollments的父母。基本上,我需要遍历两个关联才能得到我想要的标签。

我曾想过取消规范化,以便注册记录中包含我需要的数据,但我不愿意这样做。

有什么想法吗?

在Enrollment类中定义以下方法:

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查询,准备包含客户端和服务的注册集合。

最新更新