How to create a new record for a many-to-many through association that accepts nested attributes?

冷暖自知 提交于 2019-12-22 10:24:05

问题


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:


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.



来源:https://stackoverflow.com/questions/31750918/how-to-create-a-new-record-for-a-many-to-many-through-association-that-accepts-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!