【问题标题】:How to add item to json object ruby on rails?如何在rails上将项目添加到json对象ruby?
【发布时间】:2018-11-06 09:59:33
【问题描述】:

我想加入 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}

结束

【问题讨论】:

  • 用户对所有成本都是唯一的还是对每个成本都不同?
  • @UdAY 是的,看起来是这样。
  • 成本和用户之间的关联是什么?
  • @ray 提供的数据看起来如此。如果用户随成本变化怎么办?

标签: ruby-on-rails json ruby api rendering


【解决方案1】:

您可以在模型中编写自定义方法并在 index 操作中调用它,它会使用用户名返回所有成本,如下所示:

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

【讨论】:

  • 这是正确的做法
  • 更改后: {costs: Cost.cost_list } 到 {costs: Cost.list_cost } 并更改: cost_info[:user_name] = cost.user.name 到 st_info[:user_name] = User.find (cost.user_id).name 全部开始工作 谢谢大家的帮助!
【解决方案2】:

假设用户有_many 成本,

你提供了什么,

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_name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多