我想连接 2 个表中的项目。有输出:
"costs":[
{
"id":2,
"cost_name":"rent office",
"user_id":2,
"fix":true,
"amount":300300,
"created_at":"2018-11-05T18:36:19.108+06:00",
"updated_at":"2018-11-05T18:36:19.108+06:00"
},
{
"id":3,
"cost_name":"new computer",
"user_id":2,
"fix":false,
"amount":350000,
"created_at":"2018-11-06T14:44:49.805+06:00",
"updated_at":"2018-11-06T14:44:49.805+06:00"
}
],
"users":[
[
"Vi_Ok",
2
]
]
}
我想将用户参数(用户名是“Vi_Ok”)添加到每个成本中。您如何注意到两个表中都存在 userId。现在代码看起来:
def index
@costs = Cost.all
@user_name = @costs.pluck(:user_id)
@user_name = User.find(@user_name).pluck(:name, :id)
# @costs.push("name" => @user_name.pluck(:name) this one just try to add
render json: {costs: @costs, name: @user_name}
结束
您可以在您的模型中编写一个自定义方法并在索引操作中调用它,它会返回用户名的所有成本,如下所示:
def self.list_costs
cost_list = []
costs = Cost.all
costs.each do |cost|
cost_info = cost.attributes
cost_info[:user_name] = cost.user.name
cost_list << cost_info
end
cost_list
end
class CostsController < ApplicationController
def index
render json: {costs: Cost.cost_list }
end
end
我是一名优秀的程序员,十分优秀!