Rails 中的模态渲染创建信息而不是我的编辑

Modal in Rails rendering create information instead of my edit

当按下编辑按钮时,我无法在模式中呈现我的记录以进行编辑。它正在渲染一个新的 FormObject。

例如我有一个 work_sample_form 实例变量设置为 WorkSampleForm.for_work_sample(work_sample),它构建了我的工作示例 object。但是当我检查模式时,表单中的信息就像一个新的 WorkSampleForm.new()。这里有一些适用的代码让它更有意义:

当我在我的服务器上看到打印的@work_sample时,这条路线在控制器上被击中(我有一个before_action方法来设置@work_sample)

#work_sample_controller
  def edit
    p @work_sample
    respond_to do |format|
      format.js
    end
  end

我的edit.js.erb如下:

$html = "<%= escape_javascript(render '/work_samples/form', work_sample_form: WorkSampleForm.for_work_sample(@work_sample), remote: true, action: :edit) %>";
$("#work-sample-form").modal('open')

我的work_sample_formFormObject模型如下:

#work_sample_form model
  def self.for_user(user)
    new(user_id: user.id,
        title: 'New Title')
  end

def self.for_work_sample(work_sample)
    p new(
      work_sample_id: work_sample.id,
      title: work_sample.title,
      description: work_sample.description,
      start_date: work_sample.start_date,
      end_date: work_sample.end_date,
      user_id: work_sample.user_id,
      tag_ids: work_sample.tag_ids,
      attachments: work_sample.attachments
    )
  end

当我在我的模式上单击我的 'Edit' 按钮时,我看到标题为 'New Title' 我认为它是从下面初始化的,它来自触发创建选项:

<%= render 'work_samples/form_modal', work_sample_form: WorkSampleForm.for_user(current_user), remote: true %>

这是使用编辑信息填充模态的正确方法吗?对不起,如果这看起来是新手,对 Rails 还是有点陌生​​。

糟糕,发现我的错误。忘记换出新的 $html 并将其覆盖为容器中的新 html 内容。

例如:

$html = "<%= escape_javascript(render '/work_samples/form', work_sample_form: WorkSampleForm.for_work_sample(@work_sample), remote: true, action: :edit) %>"
$container = $("#work-sample-form")

$container.html($html)

$container.modal('open')