我无法弄清楚为什么current_user总是设置为user_id = 1。
当它编辑数据时,它会适当地设置user_id,但是当它创建新记录时,它会设置user_id = 1
使用rails 3.1.3 w / Devise
控制器:
def update_multiple
@user = current_user
for @workoutdate in params[:workout_workoutdates]
is_new = false
#this part works, user_id ends up equaling the current_user
@workouts = Workout.where(:user_id => @user,
:workoutdate => @workoutdate.to_time)
if !@workouts.any?
# when setting user_id to an integer it works
# for example, workout = Workout.new(:user_id => 3), it works
workout = Workout.new(:user_id => @user,
:workoutdate => @workoutdate.to_time)
is_new = true
else
workout = @workouts[0]
end
workout.save
end
终端产生的SQL:
SQL (0.7ms) INSERT INTO "intervals" ("created_at", "interval_name", "updated_at", "workout_id") VALUES (?, ?, ?, ?) [["created_at", Tue, 13 Dec 2011 03:24:28 UTC +00:00], ["interval_name", "INTERVAL"], ["updated_at", Tue, 13 Dec 2011 03:24:28 UTC +00:00], ["workout_id", nil]]
SQL (0.5ms) INSERT INTO "workouts" ("created_at", "updated_at", "user_id", "workoutdate") VALUES (?, ?, ?, ?) [["created_at", Tue, 13 Dec 2011 03:24:28 UTC +00:00], ["updated_at", Tue, 13 Dec 2011 03:24:28 UTC +00:00], ["user_id", 1], ["workoutdate", Thu, 08 Dec 2011 08:00:00 UTC +00:00]]
答案 0 :(得分:4)
我使用不同的设计。我觉得你太难了。使用devise,您可以像这样引用用户对象(锻炼):
@workouts = current_user.workouts.find(...)
然后像这样创建一个新的:
@workout = current_user.workout.build(...)
依此类推......