【问题标题】:Undefined method for backoffice controller后台控制器的未定义方法
【发布时间】:2019-12-20 18:51:25
【问题描述】:

我有与之关联的产品和 2 个控制器。 在一个(products_controller.rb)中,只有 index 和 show 方法。 另一个(backoffice / products_controller.rb)有所有的 CRUD 方法。 当我想在 backoffice / products_controller.rb 中使用 create 或 destroy 方法时,我收到一个错误,即这些方法在 products_controller.rb 中不可用。 方法 index 和 show 工作正常。

例如,我如何在 backoffice/products_controller 中使用 Destroy 方法

  def destroy
    @post.destroy
    respond_to do |format|
      format.js { render 'destroy', status: :destroy, location: @product }
      format.html { redirect_to admin_products_path, notice: 'Product was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

以及我如何调用此方法(视图/后台/产品):

<%= link_to (fa_icon "trash"), product,  method: :delete, data: { confirm: 'Are you sure?' }, class: "pull-right btn btn-outline-danger" %>

错误 - The action 'destroy' could not be found for ProductsController

路线:

  scope '/admin' do
    resources :categories, controller: 'backoffice/categories', as: "admin_categories"
    resources :products, controller: 'backoffice/products', as: "admin_products"
  end

UPD 形式:

<div class="container main">

  <%= form_with(model: product, local: true) do |form| %>

  <div class="field">
  <%= form.collection_select(:category_id, Category.all, :id, :title, class:'form-control' ) %>
</div>

  <div class="field">
      <%= form.label :title %>
      <%= form.text_field :title, class: "form-control"%>
  </div>
  <div class="field">
    <%= form.label :description %>
    <%= form.text_area :description, class: "form-control"%>
  </div>
  <br>
  <div class="text-center actions">
    <%= form.submit 'Submit', class: "btn btn-dark" %>
  </div>
  <% end %>
</div>

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    如果你查看生成的 HTML,你会发现:

    <%= link_to (fa_icon "trash"), product,  method: :delete, data: { confirm: 'Are you sure?' }, class: "pull-right btn btn-outline-danger" %>
    

    ...解析为ProductsController(类似于products/1),而不是Backoffice::ProductsController(类似于backoffice/products/1)。你可能想做更多类似的事情:

    <%= link_to (fa_icon "trash"), admin_product_path(product),  method: :delete, data: { confirm: 'Are you sure?' }, class: "pull-right btn btn-outline-danger" %>
    

    在您的表单中,您需要执行以下操作:

    <%= form_with(model: product, local: true, url: admin_products_path) do |form| %>
    

    您可能需要也可能不需要摆弄 url 位。见the docs。

    【讨论】:

    • 我应该在我的表单中进行哪些更改,以便方法 create 也有效? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2022-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多