如何使用嵌套资源CREATE操作保存current_user?

时间:2015-11-27 22:05:13

标签: ruby-on-rails ruby model-view-controller userid

MissedDate.last
 id: 32,
 user_id: nil,
 routine_id: 16,
 date_missed: Thu, 19 Nov 2015 05:00:00 EST -05:00,
 created_at: Fri, 27 Nov 2015 16:57:17 EST -05:00,
 updated_at: Fri, 27 Nov 2015 16:57:17 EST -05:00,

我们如何将user_id设置为current_user而不是nil

missed_dates_controller 中,创建操作会将@missed_date设置为routine,后者提供routine_id。或者我可以将@missed_date设置为current_user,这将提供user_id,但我需要通过创建操作保存这两个ID。

  def create
    routine = current_user.routines.find(params[:routine_id])
    routine.missed_days = routine.missed_days + 1
    routine.save
    @missed_date = routine.missed_dates.build(missed_date_params)
    @missed_date.save
    respond_modal_with @missed_date, location: root_path
  end

我非常感谢你的帮助!

1 个答案:

答案 0 :(得分:2)

如果我理解正确的问题,则需要在user_id操作中为MissedDate条记录设置create

如果这是正确的,您只需在保存记录之前分配user_id

例如:

您的创建操作:

def create
  routine = current_user.routines.find(params[:routine_id])
  routine.missed_days = routine.missed_days + 1
  routine.save
  @missed_date = routine.missed_dates.build(missed_date_params)
  @missed_date.user = current_user   # <= Here you assign the user to the to the `MissedDate` record. Please ensure that your MissedDate `belongs_to` the User model!
  @missed_date.save
  respond_modal_with @missed_date, location: root_path
end