I have a HABTM association between Users and Workspaces, which also has groups. The problem is I can't insert data intro groups from users.
class User < ActiveRecord::Base
has_and_belongs_to_many :workspaces #, dependent: :destroy
has_many :groups, through: :workspaces
end
class Workspace < ActiveRecord::Base
has_and_belongs_to_many :users, dependent: :destroy
has_many :groups, dependent: :destroy
end
This is the join table migration:
class CreateUsersAndWorkspaces < ActiveRecord::Migration
def change
create_table :users_workspaces, id: false do |t|
t.belongs_to :user, index: true
t.belongs_to :workspace, index: true
end
end
end
In rails console, when I try to create new group:
u.groups.create!(name: "txt", workspace_id: 1 )
(0.1ms) begin transaction
(0.2ms) rollback transaction
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly:
Cannot modify association 'User#groups' because it goes
through more than one other association.
Is there a way to create groups from the user?
EDIT: With help from @evedovelli I could make it work. but since user.workspace was a ActiveRecord_Associations_CollectionProxy, it was not a workspace class, but a collection. appending 'first', solved the problem, so the final code is:
u.workspaces(id: 1).first.groups.create!(name: "txt")
Now suppose I have more associations:
u.workspaces(id: 1).first.groups(id: 2).first.modelN(id:3).first.modelNplus1.create!(name: "txt")
my final question is, is this the correct way?