【问题标题】:Rails Api many to many how to send and handle jsonRails Api 多对多如何发送和处理 json
【发布时间】:2021-10-22 19:22:29
【问题描述】:

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

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表还有列号:整数。表 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。你知道如何将数字保存到表 B 中吗?

【问题讨论】:

    标签: ruby-on-rails json ruby rails-api


    【解决方案1】:

    如果除了外键之外还需要其他属性,则需要显式创建连接模型。例如:

    # 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 是连接表。如果我们想在创建公司的同时创建一个具有名称属性的职位,我们需要传递两级嵌套属性:

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

    【讨论】:

    • 好的,所以如果我想输入员工应该属于的(现有)公司的id,我应该将company_id放在json的哪里?
    • { "positions_attributes": { "name": "CEO", "company_id": 1 } }
    • 我还有一个问题。如果我想显示位置的“名称”,也许你知道我应该在序列化程序中放什么。我的意思是我希望每个员工都有 json { "company_id", "company_name", "position_name"} 。当我将 has_many :companies 通过: :positions 放入序列化程序时,我只得到 {"company_id", "company_name"} 没有“position_name”添加到位置表中的每个连接
    • 请创建一个单独的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    相关资源
    最近更新 更多