How do I create a new entry for a many-to-many association that accepts nested attributes?


and User

have a many-to-many relationship through Relationship

. I originally implemented this 1-to-many association, which worked, but now I need it to become a many-to-many association. So I created a model Relationship

and changed the association in the model files.


accepts nested attributes for User

like in my application. I have a combined registration form for the two. Also, I use it in the seed file:

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


This worked when it was a one-to-many association, but now it is a many-to-many association that occurs when seeding an error:

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


This applies to variables for the model Relationship

through which User

and are bound Organization


What is causing this error; why are these values ​​empty? Is it possible that the string Organization.create

is incorrect for a many-to-many association? member

and moderator

have default values ​​(see migration file). I expect it to create values Organization

, User

and Relationship

with default values. How else should I create a new organization and user?

Organization model:

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


Relationship model:

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


User Model:

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


Moving relationships:

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
    add_index :relationships, [:user_id, :organization_id], unique: true



source to share

1 answer

I think your problem might be that you did not specify a "foreign key" for the has_many relationship in the User Model. Try:

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


This uniquely identifies the organization for its relationship with your user model.



All Articles