【问题标题】:How to save current_user with nested resource CREATE action?如何使用嵌套资源 CREATE 操作保存 current_user?
【发布时间】:2015-11-27 22:05:13
【问题描述】:
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

非常感谢您的帮助!

【问题讨论】:

  • 您可以将:user_id=>current_user.id 添加到您的参数哈希中

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


【解决方案1】:

如果我理解的问题比您想在 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

【讨论】:

  • 这可能会起作用,但是整体建模逻辑被破坏并且会带来大量错误。我认为 TS 应该考虑多态关联
  • 我认为多态关联在这里不是正确的方法,但可能通过来自MissedDate 模型的RoutineUser 模型建立关联。这可以通过has_one :user, through: :routine 来实现。但我不知道是否每个MissedDate 记录都应该分配一个User,只是因为它分配了一个routine
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-21
相关资源
最近更新 更多