Search code examples
ruby-on-railsrubyruby-on-rails-5

Rails 5 ActiveRecord, how to include fields from associated tables?


With Rails 5, Given the models:

chef_positions
* id
* name

skills
* id
* name

chef_position_skills
* id
* chef_position_id
* skill_id

I have a controller method to return the chef_position_skills by chef_position_id:

  def index
    chef_position = ChefPosition.find(params[:chef_position_id])
    render json: chef_position.chef_position_skills
  end

This returns:

 [{"id":1,"chef_position_id":2,"skill_id":1,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"},{"id":2,"chef_position_id":2,"skill_id":2,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"}]

How can I get the controller to do the following:

  1. include skill.name for each record
  2. Do not include the timestamps

Solution

  • you need to associate the two first if you haven't already, in your model, chef_positions.rb

    has_many :skills, through: :chef_position_skills
    

    Then in your controller,

    ChefPosition.where(id: params[:chef_position_id]).joins(:skills).select('chef_positions.id, skills.name')