Rails select_tag will not access sort_to relation

I'm trying to do

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

but entity.name wont work returns an undefined method `entity.name '. "entity" refers to another model. through 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
+4
source share
3 answers

Or you add a method to your employee that you can call, for example:

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 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")
+1
source

You can add this to your Employee model:

def entity_name
  self.entity.name
end

Or you can add a delegate like this to your Employee model:

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

Then you could do:

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

"Entity" "" ( ). "entity.name". , @employees = Employer.joins(: entity).

0

Source: https://habr.com/ru/post/1589165/


All Articles