【问题标题】:How to create a new record for a many-to-many through association that accepts nested attributes?如何通过接受嵌套属性的关联为多对多创建新记录?
【发布时间】:2015-10-23 09:54:50
【问题描述】:

OrganizationUser 通过Relationship 具有多对多关联。最初我实现了一个一对多的关联,它工作但现在我需要它成为一个多对多的关联。所以我创建了Relationship 模型并更改了模型文件中的关联。

Organization 接受 User 的嵌套属性,因为在我的应用程序中,我有一个两者的联合注册表单。另外,我在种子文件中使用它:

Organization.create!(name: "name", ...).users.create(email: "email@email.com", ...)

这在它是一对多关联时有效,但现在它是一个多对多直通关联,它在播种错误时产生:

Validation failed: Member can't be blank, Moderator can't be blank 

这指的是 Relationship 模型的变量,UserOrganization 通过这些变量关联。

是什么导致了这个错误;为什么这些值是空白的?对于多对多关联,Organization.create 行可能不正确吗? membermoderator 具有默认值(请参阅迁移文件)。我希望它使用默认值创建organizationuserrelationship。我还应该如何创建新的组织和用户?


组织模式:

has_many :relationships, dependent: :destroy
has_many :users, through: :relationships

accepts_nested_attributes_for :relationships, :reject_if => :all_blank, :allow_destroy => true
validates_associated :users

关系模型:

belongs_to :organization
belongs_to :user
accepts_nested_attributes_for :user

validates_presence_of :organization
validates_presence_of :user
validates :member, presence: true
validates :moderator, presence: true

用户模型:

has_many :relationships, dependent: :destroy 
has_many :organizations, through: :relationships, inverse_of: :users

关系迁移:

class CreateRelationships < ActiveRecord::Migration
  def change
    create_table :relationships do |t|
      t.belongs_to :user, index: true
      t.belongs_to :organization, index: true

      t.boolean :member, null: false,  default: false
      t.boolean :moderator, null: false,  default: false
      t.timestamps null: false
    end
    add_index :relationships, [:user_id, :organization_id], unique: true
  end
end

【问题讨论】:

  • 您的schema.rb 是否显示正在创建的索引?也许您错过了创建索引的数据库迁移
  • Relationship 模型中的原因证明是 index: true。但是现在生成了一个验证错误。

标签: ruby-on-rails ruby ruby-on-rails-4 associations seeding


【解决方案1】:

我认为您的问题可能是您没有为用户模型中的 has_many 关系指定“外键”。试试:

has_many :relationships, foreign_key: "organization_id", dependent: :destroy

这可以根据与您的用户模型的关系唯一地标识一个组织。

【讨论】:

  • 我尝试将foreign_key: "organization_id"添加到用户模型,将foreign_key: "user_id"添加到组织模型,但播种时的错误仍然相同。但后来我发现原因是Relationship模型中的index: true。但是,现在生成了一个验证错误(请参阅原始帖子中的更新)。
猜你喜欢
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多