我试图在初始化模型后立即设置它的属性。我试过 before_initialise、after_initialise、before_create、after_create。
我究竟做错了什么?
describe "turn based system" do
before(:each) do
@user1 = Factory :user
@user2 = Factory :user
@rota = @user1.rotas.create
@rota.users << @user2
end
it "should be user1's turn at the beginning" do
@rota.current_turn.should == @user1.id --> fails
end
执行:
class Rota < ActiveRecord::Base
has_many :rotazations
has_many :users, :through => :rotazations
has_many :invitations
after_create :set_current_turn
private
def set_current_turn
if self.users.count > 0
self.current_turn = self.users[0].id
end
end
end
编辑 如果我使用以下方法构建 rota 模型:
@rota = @user1.rotas.create(:current_turn => @user1.id)
它有效——但是,我觉得我在复制代码——我总是希望 current_turn 字段成为对象创建者的 id。
谢谢!