gpt4 book ai didi

ruby-on-rails - 如何将项目添加到 json 对象 ruby​​ on rails?

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

我想连接 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

关于ruby-on-rails - 如何将项目添加到 json 对象 ruby​​ on rails?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53169565/

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