我在我的Rails 4应用程序中使用gon gem将值从我的控制器传递给JavaScript。我在我的应用程序的其他部分使用了gon,它运行正常,因此它与宝石是否正确加载无关。
我有以下型号:
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
只有来自地址模型的列,没有来自人或城市的列,例如gon.my_js_var[i].city is undefined
。
我在这里遗漏了什么吗?或者我应该以不同的方式做这件事吗?
由于
答案 0 :(得分:2)
尝试使用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 ])
答案 1 :(得分:0)
结束使用原始内连接SQL重写查询,然后在其上调用ActiveRecord::Base.connection.execute
,因此结果集包含所有记录,不包含嵌套查找。
答案 2 :(得分:0)
使用as_json
gon.my_js_var = Address.where("person_id = 1").as_json.(include: [:person,:city])