내 Rails 4 앱에서 gon gem을 사용하여 컨트롤러에서 JavaScript로 값을 전달합니다. 내 응용 프로그램의 다른 부분에 곤을 사용했습니다, 잘 작동하므로 보석이 제대로로드되었는지 여부와 관련이 없습니다. 중첩 된 레일스 ActiveRecord 쿼리 결과를 전달하는 방법은 무엇입니까?
나는 다음과 같은 모델을 가지고 :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
나는 이런 식으로 쿼리 결과를 할당 :
@my_instance_var
gon.my_js_var = @my_instance_var = Address.includes(:person, :city).where("person_id = 1")
내가, 예를 들어, 필요한 모든 값이
@my_instance_var[i].city.name
에 올바른 값이 표시됩니다. 하지만
gon.my_js_var
에는 주소 모델의 열만 있고 Person 또는 City의 항목은 없습니다.
gon.my_js_var[i].city is undefined
.
여기에 뭔가가 있습니까? 아니면 다른 방식으로해야합니까?
@my_instance_var = Address.includes(:person, :city).where("person_id = 1")
gon.my_js_var = @my_instance_var.to_json(include: [ :person, :city ])
안녕하세요 @ jiax, 나도 알아 내려고 노력하고있어, 당신이 쓴 정확한 코드를 게시 할 수 있습니까? 난 원시 SQL을 작성한 적이 없으며'ActiveRecord :: Base.connection.execute'가 – james
@james가 될지 확실하지 않기 때문에 조금 더 방향을 알고 싶다면 다음과 같이 모델에서 SQL 쿼리를 생성 할 수 있습니다 :'stmt = "SELECT * FROM TABLE"'그런 다음'result = ActiveRecord :: Base.connection.execute (stmt)'를 호출 한 다음'result'를'gon' 객체로 다시 보냅니다. – jiax