ruby-on-rails - Rails select_tag 不会访问 belongs_to 关系

标签 ruby-on-rails ruby model html-select belongs-to

我正在尝试做一个

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

但是 entity.name 不会工作抛出一个未定义的方法“entity.name”。 “实体”属于另一个模型。通过 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")

关于ruby-on-rails - Rails select_tag 不会访问 belongs_to 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30369486/

相关文章:

ruby-on-rails - Ruby/Rails - 将 Google Apps 脚本转换为 Rails

ruby - 在 irb 中访问加载源中的变量

python - Django - 基于另一个字段更新模型字段

ruby-on-rails - ruby rails : compose attribute of model from virtual attributes

ruby-on-rails - 在 Ruby 中让递减 (-=) 函数停在 0

ruby-on-rails - Date.today 和 Date.yesterday 相同但在控制台中不同

php - CRUD应用程序上的错误号1054

ruby-on-rails - 在 Controller 中排序数组

ruby - 使用几种同样抽象的语法变体来编码某些东西有什么值(value)?

model - 您是否为 MVP 及其变体中的表示层购买了重用故事?