Reputation: 21
I want to join items from 2 tables. There output:
"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
]
]
}
I want to add parameter of users (user name which is "Vi_Ok") add to every cost. How you noticed there in both table exist userId. Now code looks:
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}
end
Upvotes: 1
Views: 2070
Reputation: 1481
You can write a custom method in your model and call it in index action, which returns all the costs with the username like below:
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
Upvotes: 2
Reputation: 5552
Supposing User has_many Costs,
What you provided,
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]]}
Proceed,
costs, users = hash['costs'], hash['users']
costs.each { |c| c['user_name'] = users.detect { |u| u[1] == c['user_id'] }[0] }
Above will add user_name
in each cost hash.
Upvotes: 1