通过 options_from_collection_for_select() 使用连接和包含访问 ActiveRecord 对象

Accessing ActiveRecord Object with Joins and Includes through options_from_collection_for_select()

当我使用:

<%= @employees.first.actor.name %>
# someones name...

有效!但是当我这样做时:

options_from_collection_for_select(@employees, 'id', 'actor.name')

对于同一页面上的 select 标记,在控制器中使用相同的方法;它是:

undefined method `actor.name' for #<Employee:0x0000000b0f3218>

不是 'options_from_collection_for_select()' 前者的 shorthand 吗?为什么我会收到此错误消息?

我用过:

@employees = Employee.includes(:actor).joins(:actor)

是的,options_from_collection_for_select 是一种捷径,但它的工作原理是使用 send 调用对象上具有给定名称的方法。而且 send 不能处理像 actor.name 这样的嵌套调用。

我会通过 delegating 方法 actor_nameactor.name 来解决这个问题。将以下内容添加到您的模型中:

# app/models/employee.rb
delegate :name, to: :actor, prefix: true

然后将您的视图更改为:

options_from_collection_for_select(@employees, :id, :actor_name)