How to create a new record for a many-to-many thro

2019-05-10 04:17发布

Organization and User have a many-to-many association through Relationship. Initially I implemented this a 1-to-many association, which worked but now I need it to become a many-to-many through association. So I created the Relationship model and changed the association in the model files.

Organization accepts nested attributes for User as in my app I have a joined signup form for the two. Also, I use it in my seeds file:

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

This worked when it was a 1-to-many association but now it is a many-to-many through association, it produces upon seeding the error:

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

This refers to variables for the Relationship model, through which User and Organization are associated.

What causes this error; why are these values blank? Is the Organization.create line perhaps incorrect for a many-to-many association? member and moderator have default values (see migration file). I would expect it to create the organization, user, and relationship with default values. How else should I be creating a new organization and user?


The 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

The 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

The User model:

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

The relationship migration:

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

1条回答
时光不老,我们不散
2楼-- · 2019-05-10 04:23

I think your problem maybe that you haven't specified a "foreign key" for the has_many relationships in User Model. Try:

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

This uniquely identifies an organization per relationship with your user model.

查看更多
登录 后发表回答