我在我的项目中创建了多对多关联,它看起来是这样的:
class A < ApplicationRecord
has_many :C, through: :B
accepts_nested_attributes_for :carray
end
class B < ApplicationRecord
belongs_to :A
belongs_to :C
end
class C < ApplicationRecord
has_many :A, through: :B
end
额外的是我想在A和C之间的每个连接中保存number,所以B表额外有列number:integer。表A和表C有name列。我的控制器是这样的:
class RController < ApplicationController
...
def create
@a = A.new(a_params)
@a.save
end
...
def a_params
params.require(:a).permit([:name, carray_attributes: [:c_id, :number]])
end
end
发送json时:
{
"name" : "A name",
"carray_attributes":
[
{
"id_c": "3",
"number": "23"
},
{
"id_c": "3",
"number": "15"
}
]
}
我得到错误UnknownAttributeError:未知属性'number'为C.你知道如何将数字保存到表B吗?
如果除了外键之外还需要其他属性,则需要显式地创建连接模型。例如:
# rails g model Employee name:string
class Employee < ApplicationRecord
has_many :positions
has_many :companies, through: :positions
accepts_nested_attributes_for :positions
end
# rails g model Position name:string employee:belongs_to company:belongs_to
class Position < ApplicationRecord
belongs_to :employee
belongs_to :company
accepts_nested_attributes_for :company
end
# rails g model Company name:string
class Company < ApplicationRecord
has_many :positions
has_many :employees, through: :positions
end
这里positions
是连接表。如果我们想在创建公司的同时创建一个带有name属性的职位,我们需要传递两层嵌套属性:
Employee.create(
name: 'Bob',
positions_attributes: [
{
name: 'CEO',
company_attributes: {
name: 'Acme Corp.'
}
}
]
)