【问题标题】:How to merge two ActiveRecord queries into one hash and convert to JSON?如何将两个 ActiveRecord 查询合并为一个哈希并转换为 JSON?
【发布时间】:2016-12-29 11:14:21
【问题描述】:

我正在使用 AJAX 来获得一些结果,但问题是我正在查询两个单独的模型,并且我想将这两个模型以及它们之间的关系作为一个 JSON 对象返回。

这是我试图链接在一起的两个模型的示例 -

Car
  belongs_to :user

  :id
  :make
  :year
  :user_id

User
  has_many :cars

  :id
  :first_name
  :last_name
  :birthday

我试图让它看起来像这样 -

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

【问题讨论】:

  • 用户和汽车之间有关联吗?这些是什么?请您显示每个模型的 sn-p 吗?
  • @jaydel 好吧,我更新了问题。它只是一个标准的belongs_to/has_many 关系。

标签: ruby-on-rails json ajax activerecord


【解决方案1】:

在您的控制器中创建一个新的(私有)方法:

def format_json(users)
  result = {}
  users.each do |user|
    result[user.id] = user.formatted_data
  end
  return result
end

更改要返回的操作:

users = Users.includes(:cars).where("<your_where_clause>").limit(<n>)
render :json => { :result => format_json(users) }.to_json

app/models/user.rb

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

app/models/car.rb

class Car < ActiveRecord::Base
  def info
    {
      :id      => self.id,
      :make    => self.make,
      :year    => self.year,
      :user_id => self.user_id
    }
  end
end

【讨论】:

  • 感谢您的帮助。这应该也可以,但我只是认为我的解决方案更加独立。
【解决方案2】:

我最终使用.as_json 找到详细的here 将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 }

【讨论】:

    猜你喜欢
    • 2013-09-09
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多