【问题标题】:How do you handle an alternate create method in rails您如何处理 Rails 中的备用创建方法
【发布时间】:2016-08-30 18:35:31
【问题描述】:

我有一个模型,我希望能够只获取表单中一个字段的用户输入,然后关闭弹出窗口。这可以通过更改 create 控制器中的 respond_to 来完成。但是,对于我想要默认处理的同一个创建控制器,我有另一种形式。

即。正常的respond_to格式是

   format.html { redirect_to @pre_production_meeting, notice: 'Pre Production Meeting was successfully created.' }
   format.json { render :show, status: :created, location: @pre_production_meeting }

我想要的弹出表单的替代品是

 format.html { redirect_to controller: 'shared', action: 'window_closer', notice: 'attachment was successfully updated.' }
 format.json { render :show, status: :ok, location: @pre_production_meeting }

我知道我可以做到这一点的一种方法是设置一个变量,然后选择正确的响应,例如

if $form = '1' then 
   (first format option)
else if $form = '2' then 
   (second format option)
end

这是否是最好的方法,或者有没有办法创建另一个功能类似于 create def 但格式修改的 def?如果是这样,我无法弄清楚您如何调用使用 create2 方法来处理表单。

【问题讨论】:

  • 克里斯,我,嗯,我不明白你想做什么。你能ELi5吗?

标签: ruby-on-rails


【解决方案1】:

我看到有两种方法可以做到这一点:1. 为这种不同的逻辑创建一个新操作,或者 2. 在查询字符串中传入一个值。

如果将值传递给查询字符串,则可以使用 if 语句。

if params[:form] == '1'
  format.html { redirect_to @pre_production_meeting, notice: 'Pre Production Meeting was successfully created.' }
else
  format.html { redirect_to controller: 'shared', action: 'window_closer', notice: 'attachment was successfully updated.' }
end

(注意:您在问题中使用了$form 作为变量。由于您在它前面加上$,因此它是一个全局变量。您几乎不想在Ruby 中那样使用全局变量。它们使代码变得非常困难理解和调试。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2016-11-03
    • 2011-01-05
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多