簡體   English   中英

Rails 6 - 通過記錄創建 has_many

[英]Rails 6 - create has_many through record

為什么 CompaniesController 不使用current_user.companies.build(company_params)創建記錄 CompanyUser ? 如何在創建公司記錄時創建 CompanyUser 記錄?

楷模:

用戶

class User < ApplicationRecord
  has_many :company_users, dependent: :destroy
  has_many :companies, through: :company_users
end

公司

class Company < ApplicationRecord
  include Userstampable::Stampable

  has_many :company_users, dependent: :destroy
  has_many :users, through: :company_users

  accepts_nested_attributes_for :company_users, reject_if: :all_blank

  validates :name, presence: true, length: { maximum: 100 }
  validates :description, length: { maximum: 1000 }
end

公司用戶

class CompanyUser < ApplicationRecord
  include Userstampable::Stampable

  belongs_to :company
  belongs_to :user

  validates :company_id, presence: true
  validates :user_id, presence: true
end

公司控制器

class CompaniesController < ApplicationController
  def create
    @company = current_user.companies.build(company_params)

    respond_to do |format|
      if @company.save
        format.html { redirect_to @company, notice: 'Company was successfully created.' }
        format.json { render :show, status: :created, location: @company }
      else
        format.html { render :new }
        format.json { render json: @company.errors, status: :unprocessable_entity }
      end
    end
  end

  private

    # Never trust parameters from the scary internet, only allow the white list through.
    def company_params
      params.require(:company).permit(:name, :description)
    end
end

遷移

class CreateCompanyUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :company_users do |t|
      t.integer :role, default: 0
      t.belongs_to :company, null: false, foreign_key: true
      t.belongs_to :user, null: false, foreign_key: true

      t.timestamps null: false, include_deleted_at: true
      t.userstamps index: true, include_deleter_id: true

      t.index [:company_id, :user_id], unique: true
    end
  end
end

您需要在 CompanyUser model 中的belongs_to關聯上設置:inverse_of選項,並刪除 ComapanyUser 中的:company_id:user_id上的存在驗證以使這項工作正常進行。 ComapanyUser model 應如下所示:

class CompanyUser < ApplicationRecord
  include Userstampable::Stampable

  belongs_to :company, inverse_of: :company_users
  belongs_to :user, inverse_of: :company_users
end

檢查 ActiveRecord 關聯文檔中的:through選項的描述。 它提到您需要:inverse_of來創建連接 model 記錄。

如果您要修改關聯(而不僅僅是從中讀取),那么最好在連接 model 的源關聯上設置:inverse_of 選項。 這允許構建關聯的記錄,這些記錄將在保存時自動創建適當的連接 model 記錄。 (請參閱上面的“關聯加入模型”部分。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM