has_many绑定错误的参数

时间:2014-06-18 16:20:20

标签: ruby-on-rails has-many

我有show.html.erb

<h3>Rooms (<%= @building.rooms.count %>)</h3>
<%= render @rooms %>

我收到了这个错误:

OCIError: ORA-00904: "ROOMS"."BUILDING_ID": invalid identifier: \
SELECT "ROOMS".* FROM "ROOMS" WHERE "ROOMS"."BUILDING_ID" = :a1`

以下是模特:

class Building < ActiveRecord::Base
  has_many :rooms
end

class Room < ActiveRecord::Base
  belongs_to :building
end

这是buildings_controller.rb

class BuildingsController < ApplicationController

  def show
    @building = Building.find(params[:id])
    @rooms = @building.rooms.all
  end

building模型具有属性:

ID, NAME, CREATED_AT, UPDATED_AT, CODE

room模型具有属性:

ID, NAME, CREATED_AT, UPDATED_AT, BUILDING_CODE, NUMBER

2 个答案:

答案 0 :(得分:1)

您应该在Room

上定义明确的foreign_key
class Room < ActiveRecord::Base
  belongs_to :building, foreign_key: :code
end

通过这种方式告诉活动记录使用building.code进行查找。

当然,您还需要正确的迁移来定义room.building_code

例如

def change
  add_column :rooms, :building_code, :integer # or :string
  add_index :rooms, :building_code
end

答案 1 :(得分:0)

Room模型中,将关联更改为:

class Room < ActiveRecord::Base
  belongs_to :building, primary_key: 'code'
end

这将告诉我们关联的主键是code而不是默认的id