Ruby on rails 如何向ruby on rails上的json对象添加项?

Ruby on rails 如何向ruby on rails上的json对象添加项?,ruby-on-rails,json,ruby,api,rendering,Ruby On Rails,Json,Ruby,Api,Rendering,我想联接两个表中的项。有三个输出: "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" }, {

我想联接两个表中的项。有三个输出:

 "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}

结束

假设用户有很多成本

你提供的

hash =  {"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]]}
继续

costs, users = hash['costs'], hash['users']
costs.each { |c| c['user_name'] = users.detect { |u| u[1] == c['user_id'] }[0] }

上面将在每个成本散列中添加
user\u 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
def self.list\u成本
成本清单=[]
成本=成本
成本。每件事都有成本|
成本信息=成本属性
cost\u info[:user\u name]=cost.user.name

成本列表用户对于所有成本都是唯一的,或者对于每个成本都是不同的?@UdAY是的,看起来是这样。成本和用户之间的关联是什么?@ray提供了看起来是这样的数据。如果用户随成本变化怎么办?在将:{costs:cost.cost\u list}更改为{costs:cost.list\u cost}并将:cost\u info[:user\u name]=cost.user.name更改为st\u info[:user\u name]=user.find(cost.user\u id)之后,这是一种合适的方法。name所有操作开始谢谢您的帮助!