使用与belongs_to一起使用的build:class_name

时间:2012-07-20 02:55:48

标签: ruby-on-rails ruby ruby-on-rails-3

大家好我在使用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,而是使用insertsAssignmentsbag's id条目设置为current_user's id。有人可以帮帮我吗?我知道了。

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

2 个答案:

答案 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