How do I create a new entry for a many-to-many association that accepts nested attributes?
have a many-to-many relationship through
. 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
and changed the association in the model files.
accepts nested attributes for
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: "email@example.com", ...)
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
and are bound
What is causing this error; why are these values empty? Is it possible that the string
is incorrect for a many-to-many association?
have default values (see migration file). I expect it to create values
with default values. How else should I create a new organization and user?
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
source to share
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.
source to share