Ended up re-writing the query with a raw inner join SQL, then call ActiveRecord::Base.connection.execute
on it, so the result set contains all records, no nested lookup.
How to pass nested Rails ActiveRecord query result to gon?
-
12-07-2023 - |
Question
I'm using the gon gem in my Rails 4 app to pass values from my controller to JavaScript. I've used gon in other parts of my app, it works fine, so it's not related to whether the gem is loaded properly.
I have the following models:
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
I assign the query result like this:
gon.my_js_var = @my_instance_var = Address.includes(:person, :city).where("person_id = 1")
@my_instance_var
has all the values I need, e.g. @my_instance_var[i].city.name
shows the correct value. But, gon.my_js_var
only has the columns from Address model, nothing from Person or City, e.g. gon.my_js_var[i].city is undefined
.
Am I missing something here? Or should I be doing this a different way?
Thanks
Solution 2
OTHER TIPS
Try using to_json
as JSON
is accessible by gon
:
@my_instance_var = Address.includes(:person, :city).where("person_id = 1")
gon.my_js_var = @my_instance_var.to_json(include: [ :person, :city ])
Use as_json
gon.my_js_var = Address.where("person_id = 1").as_json.(include: [:person,:city])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow