我有一个属于2个项目实例的ActiveRecord模型'offer'。物品属于用户。
优惠模式具有以下内容:
offered_item_id receiving_item_id offering_user_id receiving_user_id
在创建模型时,我希望Rails通过读取项目ID并通过该关系来保存用户。
我有这个:
class Offer < ActiveRecord::Base
attr_accessible :offered_item_id, :receiving_item_id, :state
belongs_to :offering_user, class_name: "User"
belongs_to :receiving_user, class_name: "User"
belongs_to :offered_item, class_name: "Item"
belongs_to :receiving_item, class_name: "Item"
before_save :populate_user_ids
private
def populate_user_ids
self.receiving_user_id = self.receiving_item.user.id
self.offering_user_id = self.offered_item.user.id
end
end
但即使对populate_user_ids
方法中的值进行硬编码似乎也不起作用。我不确定before_save
是否被召唤。
我的测试是通过项目关系传递的,但是用户关系失败了。
参见我的RSpec测试:
describe "relations" do
it { should respond_to (:offering_user) }
it { should respond_to (:offered_item) }
it { should respond_to (:receiving_user) }
it { should respond_to (:receiving_item) }
its(:offering_user) { should == offering_user } #FAILS
its(:offered_item) { should == offered_item }
its(:receiving_user) { should == receiving_user } #FAILS
its(:receiving_item) { should == receiving_item }
end
道歉我对Rails很陌生。
可能是什么问题?
由于
答案 0 :(得分:0)
啊,我是个笨拙的人。
我正在使用:
let!(:offer) { offered_item.offers_made_with.build(receiving_item_id: receiving_item.id) }
而不是:
let!(:offer) { offered_item.offers_made_with.create(receiving_item_id: receiving_item.id) }
build
无法保存,create
可以保存。