2013-08-02 3 views
0

표시되지 나는이 다음 모델 :레일 모델 JSON은 협회

class OfficesController < ApplicationController 
    before_action :set_office, only: [:show, :edit, :update, :destroy] 
    respond_to :html, :json 
    def index 
    respond_with(@offices = Office.all(:include => [:company, :city])) 
    end 
    ... 

그리고 내 schema.rb :

create_table "cities", id: false, force: true do |t| 
    t.string "name",  null: false 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    create_table "companies", id: false, force: true do |t| 
    t.string "name",  null: false 
    t.string "website" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.string "acquirer_id" 
    end 

    create_table "offices", force: true do |t| 
    t.boolean "headquarters" 
    t.string "city_id" 
    t.string "company_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

class Office < ActiveRecord::Base 
    belongs_to :city 
    belongs_to :company 
end 

class Company < ActiveRecord::Base 
    has_one :acquirer 
    has_many :offices 
    has_many :cities, through: :offices 
end 

class City < ActiveRecord::Base 
    has_many :offices 
end 

내 사무실 컨트롤러가이 방법을 사용하도록 설정

나는 무엇이 잘못되었는지 정말로 모른다.

정말로 원하는 것은 company_id 및 city_id 열을 표시하는 것입니다. 나는 respond_with 메소드 없이도 JSON에서 이러한 열을 보여주는 Acquisitions Controller를 가지고있다. 그래서 나는 그것이 왜이 경우에 기본적으로 작동하는지 이해하지 못합니다. Ruby 2.0.0에서 Rails 4.0.0을 사용하고 있습니다.

+0

아마도 여러분의 문제와 관련이 없겠지만'company_id'와'city_id'를 문자열 유형으로 정의하는 것이 의도입니까? – jbh

+0

예. 그게 좋은 연습 이니? – tdkr

+0

기본적으로 ActiveRecord는 기본 키를 정수로 정의합니다. 따라서 프라이 머리 키의 타입을 변경하지 않는다면, 문자열 – jbh

답변

0

외부 키를 정의 할 때는 항상 정수를 사용해야합니다. 질문으로 돌아오고, 당신은 당신이 복잡한 JSON 응답이 있다면 난 당신이 내가이 일을하는 데 RABL 또는 jbuilder

+0

흠. 작동하지 않았습니다. 내 json 파일에 []가 표시됩니다. Rails 4와 함께 제공되는 jbuilder gem이 있다는 것을 알았 기 때문에 jbuilder 파일을 변경하면 결과가 나옵니다. – tdkr

0

보고 제안, 그러나

respond_with Office.all(:include => [:company, :city])).as_json(:include => [:company,:city]) 

를 사용할 수 있습니다.

json.array!(@offices) do |office| 
    json.extract! office, :headquarters 
    json.url office_url(office, format: :json) 
end 

에 : 그대로 컨트롤러를 떠나, 내가에서 index.json.jbuilder을 변경

json.array!(@offices) do |office| 
    json.extract! office, :headquarters, :company_id, :city_id 
    json.url office_url(office, format: :json) 
end 

너희들이 수정 프로그램이 어떻게 생각하는지 확실하지?