gpt4 book ai didi

ruby-on-rails - Rails 5 ActiveRecord,如何包含关联表中的字段?

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:11 25 4
gpt4 key购买 nike

对于 Rails 5,给定模型:

chef_positions
* id
* name

skills
* id
* name

chef_position_skills
* id
* chef_position_id
* skill_id

我有一个 Controller 方法通过 chef_position_id 返回 chef_position_skills:

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

返回:

 [{"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"}]

如何让 Controller 执行以下操作:

  1. 为每条记录包含 skill.name
  2. 不包含时间戳

最佳答案

如果您还没有在您的模型中将两者关联起来,则需要先将两者关联起来,chef_positions.rb

has_many :skills, through: :chef_position_skills

然后在你的 Controller 中,

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

关于ruby-on-rails - Rails 5 ActiveRecord,如何包含关联表中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44381564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com