RailsApi多对多如何发送和处理json

Rails Api many to many how to send and handle json

我在我的项目中创建了多对多关联,看起来像这样:

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 之间的每个连接中保存数字,所以 B table 有额外的列 number:integer。 Table A 和 C 有名称栏。我的 AController 看起来像这样:

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: unknown attribute 'number' for C。你知道如何将数字保存到 table 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是连接table。如果我们想在创建公司的时候创建一个带有名称属性的职位,我们需要传递两层嵌套属性:

Employee.create(
  name: 'Bob',
  positions_attributes: [
    {
      name: 'CEO',
      company_attributes: {
        name: 'Acme Corp.'
      }
    } 
  ]
)