我有三个模特。两个是通过has_and_belongs_to_many关联与适当的联接表相关联的,另一个是与has_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我可以以以下方式创建具有颜色的新项目:
@item = Item.new(name: "ball")
@item.users << @user
@item.save
@item.colors.create!(name: "blue")该项现在链接到@user引用的用户。
但我认为必须有另一种方式为用户创建项目,比如我添加颜色的方式。
@user.item.create!(name: "car")这不起作用,因为创建的项的用户数组是空的,并且该项现在不属于用户。
这种方法有什么问题?
发布于 2013-11-13 08:17:55
不应使用has_and_belongs_to_many。( github )
相反,使用带直通标志的has_many:guides.rubyonrails.org...
类似于:
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这看起来可能很复杂,但它会解决你的问题。此外,考虑到许多项共享相同颜色的情况,如果没有联接表,则更难以按颜色对项进行分类。
https://stackoverflow.com/questions/19948388
复制相似问题