I have three models. Two are related through a has_and_belongs_to_many
association with the appropriate join table and one with an has_many
association.
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
I can create new items with a color in the following way:
@item = Item.new(name: "ball")
@item.users << @user
@item.save
@item.colors.create!(name: "blue")
The item is now linked to the user referenced by @user
.
But I think there has to be another way to create items for users, like the way I added the color.
@user.item.create!(name: "car")
This doesn't work because the users-array of the created item is empty and the item does now not belong to a user.
What is the problem with this approach?