Pregunta

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

¿Fue útil?

Solución 2

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.

Otros consejos

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])
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top