【问题标题】:How to render format JavaScript in a Rails controller如何在 Rails 控制器中呈现格式 JavaScript
【发布时间】:2020-04-04 12:23:26
【问题描述】:

我有一个叫"/admin"的路由,用于添加和列出产品,来自:

resources :products, controller: "admin"

在控制器管理员中我有一个create 函数:

  def create
    @product = Product.new product_values
    respond_to do |format|
      if @product.save
        format.html { redirect_to :root }
      else
        format.js { render 'admin/error' }
      end
    end
  end

当我试图让它渲染到 format.js 时,它说:

ActionController::UnknownFormat
on `respond_to do |format|`

我以为创建了admin/create.js.haml

console.log("got it")

但它不起作用。

为什么我希望响应是“format.js”?因为我想在表单中添加错误消息并且不想刷新页面,所以我在某个 div 上用 JavaScript 回复 append 并带有错误消息。

这是admin/add_product.html.haml

.p-5
  .container.column.justify-content-center
    %div.d-flex.justify-content-center.p-4#this-error
      %div
        %h3
          Add Product
    %div
      = form_for (@product || Product.new) do |f|
        .form-group.row
          = f.label :name,  class: 'col-md-2 col-form-label'
          %br/
          .col-sm-8
            = f.text_field :name, class: 'form-control'
        .form-group.row
          = f.label :stock,  class: 'col-md-2 col-form-label'
          %br/
          .col-sm-2
            = f.number_field :stock, class: 'form-control'
          .my-4
          = f.label :price,  class: 'ml-5 col-md-1 col-form-label'
          %br/
          .col-sm-2
            = f.number_field :price, class: 'form-control'
        .form-group.row
          = f.label :desc,  class: 'col-md-2 col-form-label'
          %br/
          .col-sm-8
            = f.text_area :desc, class: 'form-control'
        .d-flex.justify-content-center
          = f.submit "Add", class: 'btn btn-primary col-sm-8 p-2'

我如何在 Haml 中使用 format.js?

【问题讨论】:

  • format.html 是 html 请求的处理程序,format.js 是 ajax 请求的处理程序。您必须正常提交表单而不是 AJAX,因此会出现此错误。也分享你的haml代码。
  • 刚刚做了,检查上面:D @AmitPatel
  • 我想在id: #this-error 上添加错误消息,所以我需要在表单为空时使用javascript 来不刷新页面,所以当我提交"Add" 时,表单为空并且必须得到错误信息
  • 如果要发出 ajax 请求,请将 remote: true 添加到表单中
  • 我必须把它放在哪里??

标签: javascript ruby-on-rails ruby haml erb


【解决方案1】:

您是通过表单提交本地请求,而不是远程(AJAX 请求)所以您的

format.js 

永远不会被调用。

你可以做的是:

def create
    @product = Product.new product_values
    respond_to do |format|

        format.html { 
          if @product.save
             redirect_to :root
          else
             render 'admin/error'
           end
           }
        format.js {  }

    end
  end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多