首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ActiveRecord::Associations::CollectionProxy HABTM创建/构建无效

ActiveRecord::Associations::CollectionProxy HABTM创建/构建无效
EN

Stack Overflow用户
提问于 2013-11-13 07:59:40
回答 1查看 515关注 0票数 0

我有三个模特。两个是通过has_and_belongs_to_many关联与适当的联接表相关联的,另一个是与has_many关联的。

代码语言:javascript
复制
class Item < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_many :colors
end

class Color < ActivRecord::Base
  belongs_to :item
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :items
end

我可以以以下方式创建具有颜色的新项目:

代码语言:javascript
复制
@item = Item.new(name: "ball")
@item.users << @user
@item.save

@item.colors.create!(name: "blue")

该项现在链接到@user引用的用户。

但我认为必须有另一种方式为用户创建项目,比如我添加颜色的方式。

代码语言:javascript
复制
@user.item.create!(name: "car")

这不起作用,因为创建的项的用户数组是空的,并且该项现在不属于用户。

这种方法有什么问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-13 08:17:55

不应使用has_and_belongs_to_many。( github )

相反,使用带直通标志的has_many:guides.rubyonrails.org...

类似于:

代码语言:javascript
复制
class Item < ActiveRecord::Base
  has_many :user_items
  has_many :users, through: :user_items # I can never think of a good name here

  has_many :colors
  has_many :item_colors, through: :colors
end

class Color < ActiveRecord::Base
  has_many :item_colors
  has_many :items, through: :item_colors
end

class User < ActiveRecord::Base
  has_many :user_items
  has_many :items, through: :user_items
end

class ItemColor < ActiveRecord::Base
  belongs_to :item
  belongs_to :color
end

class UserItem < ActiveRecord::Base
  belongs_to :user
  belongs_to :item
end

这看起来可能很复杂,但它会解决你的问题。此外,考虑到许多项共享相同颜色的情况,如果没有联接表,则更难以按颜色对项进行分类。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19948388

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档