Rails 4中的has_and_belongs_to_many关系

时间:2014-06-05 10:18:49

标签: ruby-on-rails

我需要在BeautySalonEmployee和BeautySalonService模型之间添加关系。有以下迁移:

class CreateBeautySalonEmployeesBeautySalonServices < ActiveRecord::Migration
  def change
    create_table :beauty_salon_employees_beauty_salon_services, id: false do |t|
        t.belongs_to :beauty_salon_employee
        t.belongs_to :beauty_salon_service
    end

    add_index :beauty_salon_employees_beauty_salon_services, [:beauty_salon_employee_id, :beauty_salon_service_id], unique: true, name: 'employee_service'
    add_index :beauty_salon_employees_beauty_salon_services, :beauty_salon_employee_id, name: 'employee'
    add_index :beauty_salon_employees_beauty_salon_services, :beauty_salon_service_id,  name: 'service'
  end
end

型号:

class BeautySalonEmployee < ActiveRecord::Base
  has_and_belongs_to_many           :beauty_salon_services
end

class BeautySalonService < ActiveRecord::Base
    has_and_belongs_to_many :beauty_salon_employees
end

现在,当我尝试执行以下命令时:

BeautySalonEmployee.first.beauty_salon_services.build

我收到以下错误:

ActiveRecord::StatementInvalid: Could not find table 'beauty_salon_employees_services'

我错了什么?提前致谢。

1 个答案:

答案 0 :(得分:1)

在您的模型中提供 join_table 选项

class BeautySalonEmployee < ActiveRecord::Base
  has_and_belongs_to_many :beauty_salon_services,:join_table => :beauty_salon_employees_beauty_salon_services
end

class BeautySalonService < ActiveRecord::Base
  has_and_belongs_to_many :beauty_salon_employees,:join_table => :beauty_salon_employees_beauty_salon_services
end

目前Rails正在寻找一个不存在的表格 beauty_salon_employees_services 。所以你必须提到这样的连接表。

<强> Source