[英]How to merge two ActiveRecord queries into one hash and convert to JSON?
I'm using AJAX to get some results, but the problem is I'm querying two separate models and I want to return both and their relationship to one another as one JSON object. 我正在使用AJAX来获得一些结果,但是问题是我正在查询两个单独的模型,并且我想将两者及其相互关系作为一个JSON对象返回。
Here's an example of two models I'm trying to link together - 这是我尝试链接在一起的两个模型的示例-
Car
belongs_to :user
:id
:make
:year
:user_id
User
has_many :cars
:id
:first_name
:last_name
:birthday
I'm trying to get it to look something like this - 我正在尝试使其看起来像这样-
{
1: {
id: 1,
first_name: 'Joe'
last_name: 'Smith'
cars: {
23: {
id: 23,
make: 'BMW',
year: 2009,
user_id: 1
},
24: {
id: 24,
make: 'Volvo',
year: 2012,
user_id: 1
}
}
},
2: {
id: 2,
first_name: 'Bob'
last_name: 'Johnson'
cars: {
35: {
id: 35,
make: 'Ford',
year: 2013,
user_id: 2
}
}
}
}
Create a new (private) method in your controller: 在控制器中创建一个新的(私有)方法:
def format_json(users)
result = {}
users.each do |user|
result[user.id] = user.formatted_data
end
return result
end
Change the action to return: 更改操作以返回:
users = Users.includes(:cars).where("<your_where_clause>").limit(<n>)
render :json => { :result => format_json(users) }.to_json
class User < ActiveRecord::Base
def formatted_data
{
:id => self.id,
:first_name => self.first_name,
:last_name => self.last_name,
:cars => self.get_car_info
}
end
def get_car_info
car_info = {}
self.cars.each do |car|
car_info[car.id] = car.info
end
return car_info
end
end
class Car < ActiveRecord::Base
def info
{
:id => self.id,
:make => self.make,
:year => self.year,
:user_id => self.user_id
}
end
end
I ended up using the .as_json
I found detailed here to convert ActiveRecord to a plain Ruby hash and passed that hash to the view. 我最终使用了
.as_json
我在这里找到了详细信息)将ActiveRecord转换为纯Ruby哈希并将该哈希传递给视图。
user = User.find(params[:user_id].to_i)
@json = {}
@json[user.id] = user.as_json
@json[user.id]['cars'] = {}
user.cars.each do |car|
@json[user.id]['cars'][car.id] = car.as_json
end
render json: { status: true, users: @json }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.