0

私は次のモデルを持っています:

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

私の Offices コントローラーは次のように設定されています。

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

何が悪いのかよくわかりません。

本当に必要なのは、company_id 列と city_id 列を表示することだけです。Respond_with メソッドがなくても JSON でこれらの列を表示する Acquisitions Controller があります。そのため、この場合ではなくデフォルトで機能する理由がわかりません。Ruby 2.0.0 で Rails 4.0.0 を使用しています。

4

2 に答える 2

0

私はそれを働かせました。コントローラーはそのままにして、 index.json.jbuilder を次のように変更しました。

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

に:

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

この修正についてどう思うかわかりませんか?

于 2013-08-02T10:42:07.793 に答える
0

外部キーの定義には常に整数を使用する必要があります。質問に戻って、使用できます

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

ただし、複雑な JSON 応答がある場合は、RABLまたはjbuilderを検討することをお勧めします。

于 2013-08-02T10:06:58.450 に答える