我通过修改参数而不是在表单中创建 hidden_field 来设置用户。据我了解,这是一种更安全的批量分配方式。
def update
@exercise = Exercise.find(params[:id])
#this is the important part
if params[:exercise][:log_entries_attributes].present?
params[:exercise][:log_entries_attributes].each do |value|
value[1].merge!(:user_id => current_user.id)
end
end
#end the important part
respond_to do |format|
if @exercise.update_attributes(params[:exercise])
format.html { redirect_to_back_or_default @exercise, notice: "Exercise was successfully updated." }
format.mobile { redirect_to @exercise, notice: 'Exercise was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.mobile { redirect_to @exercise, notice: "#{@exercise.errors.full_messages.to_sentence}" }
format.json { render json: @exercise.errors, status: :unprocessable_entity }
end
end
end
在我的规范中,我有以下内容:
describe "with log_entry_attributes" do
it "updates log_entries_attributes and sets user" do
exercise = FactoryGirl.create(:exercise)
log_entry = FactoryGirl.build(:log_entry)
exercise.log_entries << log_entry
exercise.save
controller.stub(:current_user).and_return(@user)
put :update, :id => exercise.id, :exercise => FactoryGirl.build(:exercise, "log_entries_attributes" => {":0" => {"reps" => "5", "weight" => "5"}}).attributes.symbolize_keys
assigns(:exercise).log_entries.first.user.should eq(@user)
end
end
我明白了undefined method user for nil:NilClass
。我想我知道为什么我会得到未定义的方法用户。只是没有办法通过分配获得关联。我不确定如何测试 user_id 是否通过 current_user 正确设置。有什么帮助吗?