【问题标题】:How to pass nested Rails ActiveRecord query result to gon?如何将嵌套的 Rails ActiveRecord 查询结果传递给 gon?
【发布时间】:2014-04-30 06:18:38
【问题描述】:

我在我的 Rails 4 应用程序中使用 gon gem 将值从我的控制器传递到 JavaScript。我在我的应用程序的其他部分使用了 gon,它工作正常,所以它与 gem 是否正确加载无关。

我有以下型号:

class Person < ActiveRecord::Base
    has_many :addresses
  end

class Address < ActiveRecord::Base
  belongs_to :person
  belongs_to :city
end

class City < ActiveRecord::Base
  has_many :addresses
end

我这样分配查询结果:

gon.my_js_var = @my_instance_var = Address.includes(:person, :city).where("person_id = 1")

@my_instance_var 具有我需要的所有值,例如@my_instance_var[i].city.name 显示正确的值。但是,gon.my_js_var 仅包含来自 Address 模型的列,没有来自 Person 或 City 的列,例如gon.my_js_var[i].city is undefined.

我在这里遗漏了什么吗?还是我应该以不同的方式来做这件事?

谢谢

【问题讨论】:

    标签: javascript ruby-on-rails json ruby-on-rails-4 rubygems


    【解决方案1】:

    尝试使用to_json,因为JSON 可以通过gon 访问:

    @my_instance_var = Address.includes(:person, :city).where("person_id = 1")
    gon.my_js_var = @my_instance_var.to_json(include: [ :person, :city ])
    

    【讨论】:

    • to_json 返回一个字符串表示,有什么方法可以在一个对象中返回完整的查询结果?
    【解决方案2】:

    最终使用原始内连接 SQL 重写查询,然后在其上调用 ActiveRecord::Base.connection.execute,因此结果集包含所有记录,没有嵌套查找。

    【讨论】:

    • 嗨@jiax,我也在尝试解决这个问题,你能发布你写的确切代码以及在什么文件中吗?我希望有更多的方向,因为我从未编写过原始 SQL,并且不确定 ActiveRecord::Base.connection.execute 的去向
    • @james,您可以在模型中构造 SQL 查询,例如:stmt = "SELECT * FROM TABLE",然后是 result = ActiveRecord::Base.connection.execute(stmt),然后将 result 传回给您 gon 对象
    【解决方案3】:

    使用as_json

    gon.my_js_var = Address.where("person_id = 1").as_json.(include: [:person,:city])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-11
      • 2017-03-23
      • 1970-01-01
      • 2011-10-25
      • 2021-04-05
      • 1970-01-01
      • 2020-11-12
      • 2020-12-31
      相关资源
      最近更新 更多