Rails select_tag 将不会访问 belongs_to 关系

Rails select_tag will not access belongs_to relation

我正在尝试

select_tag "employee_compensation_benefits_selection", options_from_collection_for_select(@employees, "id", "entity.name", "1")

但 entity.name 将无法工作并抛出未定义的方法“entity.name”。 "entity"属于另一个模型。通过 entity_id

class Employee < ActiveRecord::Base

  include UUIDHelper

  belongs_to :entity
  has_one :status
  has_many :restdays
  has_one :regular_work_period

  validates_presence_of :entity

end

require 'file_size_validator'
class Entity < ActiveRecord::Base

  include UUIDHelper

  has_one :access, autosave: true
  has_one :employee, autosave: true
  has_many :contact_detail, autosave: true
  has_many :file_set
  has_many :link_set

  mount_uploader :logo, AvatarUploader
  validates_presence_of :name
  validates :name, uniqueness: true
  validates_length_of :description, maximum: 256

  validates :logo,
        :file_size => {
            :maximum => 25.megabytes.to_i
        }
end

您可以向您的员工添加一个可以调用的方法,例如:

class Employee < ActiveRecord::Base
  ...

  def entity_name
    self.entity.name
  end
end

然后:

select_tag "employee_compensation_benefits_selection", options_from_collection_for_select(@employees, "id", "entity_name", "1")

或者您可以使用 lambda 而不是添加方法:

select_tag "employee_compensation_benefits_selection", options_from_collection_for_select(@employees, "id", lambda { |employee| employee.entity.name }, "1")

您可以将此添加到您的员工模型中:

def entity_name
  self.entity.name
end

或者您可以将这样的委托添加到您的 Employee 模型中:

delegate :name, :to => :entity, :prefix => true

那么你可以这样做:

select_tag "employee_compensation_benefits_selection", options_from_collection_for_select(@employees, "id", "entity_name", "1")

'Entity' 模型引用数据库中的 table 名称 'entities'(除非您覆盖了 table 名称的默认值)。请改用 "entities.name"。如果您加入了结果 @employees = Employer.joins(:entity).

,这将起作用