Question

I did some research. Rails 3 use :select to inject the SQL to it, but deprecated in Rail 4.

How can I archive this easily?

For example in the following models. I want

boss.employees[0].salary

Models

class Boss < ActiveRecord::Base
    has_many :employments
    has_many :employees, :through => :employments
end

class Employee < ActiveRecord::Base
    has_many :employments
    has_many :bosses, :through => :employments
end

Employments Migration:

class CreateEmployments < ActiveRecord::Migration
    def change
      create_table :employments do |t|
        t.integer :boss_id
        t.integer :employee_id
        t.decimal :salary

        t.timestamps
      end
    end
end
Was it helpful?

Solution

OK. I found something.

class Boss < ActiveRecord::Base
  has_many :employments
  has_many :employees, -> { select('employees.*, employment.salary as salary') } :through => :employments
end

OTHER TIPS

I know this post is a bit old, but I think you missed something. Your classes look fine, so does the Employment model. You did not post the Class Employment, so I am assuming it is the missing link in your system.

class Employment < ActiveRecord::Base

    belongs_to :boss
    belongs_to :employee

end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top