通过HABTM插入数据

时间:2016-04-17 00:29:44

标签: ruby-on-rails activerecord has-and-belongs-to-many

我在用户和工作区之间有一个HABTM关联,它也有组。问题是我无法从用户插入数据介绍组。

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

这是连接表迁移:

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

在rails控制台中,当我尝试创建新组时:

 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.

有没有办法从用户创建群组?

编辑: 在@evedovelli的帮助下,我可以让它发挥作用。但由于user.workspace是ActiveRecord_Associations_CollectionProxy,因此它不是工作空间类,而是集合。附加'first',解决了问题,所以最终的代码是:

u.workspaces(id: 1).first.groups.create!(name: "txt")

现在假设我有更多关联:

u.workspaces(id: 1).first.groups(id: 2).first.modelN(id:3).first.modelNplus1.create!(name: "txt")

我的最后一个问题是,这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

问题是Rails无法找到用户工作区应该添加(即使您要指定像你一样,在创造中的worspace_id。)

如错误消息中所述,HasManyThrough的嵌套关联是只读的。因此,您可以直接从用户阅读群组,但无法创建它们。

由于您在创建群组时知道workspace_id,因此您只需使用以下内容创建群组:

u.workspaces.find_by_id(1).groups.create!(name: "txt")

这样,它会为正确的用户工作区创建

你应该能够通过其他协会继续这样做:

u.workspaces.find_by_id(1).groups.find_by_id(2).modelN.find_by_id(3).modelNplus1.create!(name: "txt")