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

时间:2018-07-07 18:09:34

标签: ruby-on-rails ruby controller erb

按编辑按钮时,将记录呈现在模式中进行编辑时出现问题。而是呈现一个新的FormObject。

例如我有一个work_sample_form实例变量,设置为WorkSampleForm.for_work_sample(work_sample),可以构建我的工作样本对象。但是,当我检查模态时,表单中的信息就像新的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_form FormObject模型如下:

#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

当我单击我的模态上的“编辑”按钮时,我看到标题为“新标题”,我假设它是从下面初始化的,这是从触发创建选项开始的:

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

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

1 个答案:

答案 0 :(得分:0)

糟糕,发现了我的错误。忘记换出新的$ 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')