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
最佳答案
我认为您的问题可能是您没有为用户模型中的 has_many 关系指定“外键”。尝试:
has_many :relationships, foreign_key: "organization_id", dependent: :destroy
这会根据与您的用户模型的关系唯一地标识一个组织。
关于ruby-on-rails - 如何通过接受嵌套属性的关联为多对多创建新记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750918/