HABTM无法正常工作 - 未知绑定

时间:2014-07-10 12:14:58

标签: ruby-on-rails-4 has-and-belongs-to-many

我创建了三个模型:

class Role < ActiveRecord::Base
    has_many :users
    has_and_belongs_to_many :permissions
    accepts_nested_attributes_for :users, :permissions
end

class Permission < ActiveRecord::Base
    has_and_belongs_to_many :roles
    accepts_nested_attributes_for :roles
end

和迁移如下:

class Changetable < ActiveRecord::Migration
  def change
    create_table :permissions_roles, id: false do |t|       
        t.belongs_to :permissions      
        t.belongs_to :roles
    end
  end
end

这样可以使用在我的sql数据库中看起来完全相同的schema.rb:

  create_table "permissions", force: true do |t|
    t.string   "subject_class"
    t.string   "subject_id"
    t.string   "action"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "permissions_roles", id: false, force: true do |t|
    t.integer "permissions_id"
    t.integer "roles_id"
  end

  create_table "roles", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

现在,当我调用Roles.first.permissions时,我收到以下错误消息:

irb(main):001:0> Role.first.permissions
  ←[1m←[36mSQL (1.0ms)←[0m  ←[1mUSE [rails_confreport_develop]←[0m
  ←[1m←[35mRole Load (2.0ms)←[0m  EXEC sp_executesql N'SELECT TOP (1) [roles].* FROM [roles] ORDER BY [roles].[id] ASC'
RuntimeError: Unknown bind columns. We can account for this.

如果我拨打Permission.first.roles,也会发生同样的情况!我错过了什么?

祝你好运!

1 个答案:

答案 0 :(得分:1)

错误是我的联合表中的外键拼写。

改变了这个:

  create_table "permissions_roles", id: false, force: true do |t|
    t.integer "permissions_id"
    t.integer "roles_id"
  end

到此:

  create_table "permissions_roles", id: false, force: true do |t|
    t.integer "permission_id"
    t.integer "role_id"
  end

它有效。