大家好我在使用build
Bag
belongs_to :creator, :class_name => "User"
has_many :users, :through => :assignments
User
has_many :bags, :through => :assignments
Assignment
attr_accessible :bag_id, :user_id
belongs_to :bag
belongs_to :user
我只是想创建一个正确使用Bag
来设置外键的current_user's id
。但是一直在发生的是
Rails正确创建Bag
但不是将Bag.creator_id设置为current_user.id,而是使用inserts
和Assignments
将bag's id
条目设置为current_user's id
。有人可以帮帮我吗?我知道了。
current_user.bags.build type: "Prada", price: 50
current_user.save
答案 0 :(得分:1)
似乎User
只知道通过assignments
的行李,这就是为什么它正在使用它。如果你想跳过rel表,你真正需要的是creator
等效的包:
User
has_many :bags, :through => :assignments
has_many :creations, :class_name => 'Bag'
bag = current_user.creations.build type: "Prada", price: 50
bag.save
答案 1 :(得分:0)
我认为你的模型应该是这样的
Bag
belongs_to :creator, :class_name => "User"
has_many :assignments
has_many :users, :through => :assignments
User
has_many :assignments
has_many :bags, :through => :assignments
Assignment
belongs_to :bag
belongs_to :user
attr_accessible :bag_id, :user_id
尝试
bag = current_user.bags.build type: "Prada", price: 50
bag.save
或
current_user.bags.create type: "Prada", price: 50