Ruby on rails ActiveRecord::Associations::CollectionProxy HABTM创建/生成不工作

Ruby on rails ActiveRecord::Associations::CollectionProxy HABTM创建/生成不工作,ruby-on-rails,activerecord,model,associations,has-and-belongs-to-many,Ruby On Rails,Activerecord,Model,Associations,Has And Belongs To Many,我有三种型号。两个通过一个has\u和一个has\u many关联与适当的联接表相关联,一个与has\u many关联 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 ha

我有三种型号。两个通过一个
has\u和一个
has\u many
关联与适当的联接表相关联,一个与
has\u many
关联

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
这不起作用,因为所创建项的用户数组为空,并且该项现在不属于用户


这种方法有什么问题

has_和_属于_许多不应该使用。(

相反,使用带有直通标志的has_many:

比如:

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
class项

它可能看起来很复杂,但它会解决你的问题。同时,考虑到许多项目共享同一颜色的情况,如果没有一个连接表,那么用颜色对项目进行分类是比较困难的。

你不创建新的项目,只需创建<代码>项目=项目。新的(名称:“球”)< /C> > <代码> @ item = item。创建(名称:“球”)
我不这么认为。
@item=item.new
+
@item.save
类似于
item.create
。但这不是问题。我已经尝试过,我会再试一次,但我不希望它只有一个用于关联的额外模型。好的,谢谢。它现在可以工作了。但是我如何防止创建未分配给项目的项目用户?我在项目模型中添加了
验证:用户,状态:true
,但这不起作用。好的,谢谢,这个答案解决了我的一个问题。我将用另一个问题写另一个问题。我相信这会有帮助:额外的模型将真正解放你。如果你希望用户能够拥有一个以上的特定项目,该怎么办。数量计数将正好适合UserItem。
@user.item.create!(name: "car")
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