Search code examples
ruby-on-railsrubymodelhtml-selectbelongs-to

Rails select_tag will not access belongs_to relation


I am trying to do a

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

but entity.name wont work throws an undefined method `entity.name'. "entity" belongs to another model. through an 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

Solution

  • Either you add a method to your employee that you can call, like:

    class Employee < ActiveRecord::Base
      ...
    
      def entity_name
        self.entity.name
      end
    end
    

    and then:

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

    or you can use a lambda instead of adding a method:

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