Rails - 如何在使用时显式指定外键:在控制器中包含方法

时间:2014-03-10 15:29:15

标签: ruby-on-rails activerecord

我有一个Rails控制器,我正在尝试返回一个json对象,该对象由从遗留SQL Server数据库派生的几个关联模型组成。由于我是新手并且正在尝试,我只在一个相关模型上使用“:include”,直到我可以使其工作,然后提高赌注。

控制器:

class SlotMachineEntityController < ApplicationController
  def retrieveAll
      @blah = Machine.where("Machine.CasinoID = 2").find(1, :select => "Machine.MachineID", :include => :slot_instance)

      respond_to do |format|
          format.json { render :json => @blah }
      end
  end
end

错误是:

  

TinyTds ::错误:列名“ machine_id ”无效:......   [Master]。[SlotInstance]。[Active] AS t1_r10 FROM [Master]。[Machine]   LEFT OUTER JOIN [Master]。[SlotInstance] ON   [Master]。[SlotInstance]。[ machine_id ] = [Master]。[Machine]。[MachineID]   WHERE [Master]。[Machine]。[MachineID] = @ 0 AND(Machine.CasinoID = 2)',   N'@ 0 int',@ 0 = 1

推测错误发生在它尝试执行“:include =&gt;:slot_instance”并通过查找“machine_id”而不是“MachineID”(这是数据库中使用的密钥)而恢复为默认命名约定。我找不到我指定的语法:include方法,外键是MachineID而不是machine_id。

供参考,相关型号为:

class Machine < ActiveRecord::Base
    self.table_name = "Master.Machine"
    set_primary_key "MachineID"

    has_one :slot_instance
    belongs_to :manufacturer, :foreign_key => "ManufacturerID"
    belongs_to :casino, :foreign_key => "CasinoID"
    belongs_to :customer, :foreign_key => "CustomerID"
end

class SlotInstance < ActiveRecord::Base
    self.table_name = "Master.SlotInstance"
    set_primary_key "SlotInstanceID"

    belongs_to :game_configuration, :foreign_key => "GameConfigurationID"
    belongs_to :customer, :foreign_key => "CustomerID"
    belongs_to :casino, :foreign_key => "CasinoID"
    belongs_to :location, :foreign_key => "LocationID"
    belongs_to :machine, :foreign_key => "MachineID"
end

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您需要在机器类的has_one关系中指定外键,即

has_one :slot_instance, :foreign_key => "MachineID"