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

How to save current_user with nested resource CREATE action?

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

非常感谢您的帮助!

如果我理解的问题比你想在 create 操作中为你的 MissedDate 记录设置 user_id

如果这是正确的,那么您只需在保存记录之前分配 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