【问题标题】:Calling a controller method from a button in rails从 Rails 中的按钮调用控制器方法
【发布时间】:2017-05-13 23:36:05
【问题描述】:

我看到这个问题之前已经被问过好几次了(即herehere,仅举几例),但我无法让它与我的案例一起使用。我正在使用 Rails 5。

我的posts_controller 中有一个名为scrape 的方法。它创建了几个对象实例。

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def scrape
    destroy_old_data
    @some_var = Scrape.create("something")
  end
  ...
end

我想在views/posts/index.html.erb 中为scrape 方法创建一个按钮,但我无法让该按钮工作。我太习惯使用脚手架方法了,不知道如何创建自定义方法。

我尝试过的一些方法:

<%= button_to "scrape", action: "scrape"%>

<%= "scrape me", { :controller => "posts", :action => "scrape"}, class: 'btn btn-primary' %>

<%= button_to "scrape", posts_scrape_path %>

如何在index.html.erb 中创建一个触发scrape 方法的scrape 按钮?我是否也需要修改我的路线?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您还需要创建一条新路线

    post 'scrape' => 'posts#scrape', as: :scrape
    

    那么你就可以访问scrape_pathscrape_url

    button_to 'Scrape', scrape_path
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      相关资源
      最近更新 更多