0

大家好,我在使用时遇到问题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的条目。有人可以帮我吗?我无计可施。Assignmentsbag's idcurrent_user's id

current_user.bags.build type: "Prada", price: 50
current_user.save
4

2 回答 2

1

似乎User只知道包包,assignments这就是它使用它的原因。creator如果您想跳过 rel 表,您真正需要的是包的等价物,例如:

User
 has_many :bags, :through => :assignments
 has_many :creations, :class_name => 'Bag'

bag = current_user.creations.build type: "Prada", price: 50
bag.save
于 2012-07-20T18:05:10.013 回答
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
于 2012-07-20T04:41:31.743 回答