【发布时间】:2015-10-23 09:54:50
【问题描述】:
Organization 和User 通过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 模型的变量,User 和 Organization 通过这些变量关联。
是什么导致了这个错误;为什么这些值是空白的?对于多对多关联,Organization.create 行可能不正确吗? member 和 moderator 具有默认值(请参阅迁移文件)。我希望它使用默认值创建organization、user 和relationship。我还应该如何创建新的组织和用户?
组织模式:
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