我对rails非常陌生。我试图只在单击链接时调用函数check(),但控制器也会在每次加载视图时调用该函数。使用link_to仅在链接被点击时调用rails中的函数
途径: routes.rb中
Rails.application.routes.draw do
get 'welcome/index'
resources :articles
控制器: articles_controller.rb
class ArticlesController < ApplicationController
helper_method :check
def new
end
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
def check
puts "check"
end
def show
@article = Article.find(params[:id])
end
def index
@articles = Article.all
end
private
def article_params
params.require(:article).permit(:title, :text)
end
型号: article.rb
class Article < ActiveRecord::Base
end
查看: index.html.erb
<h1>
<%= link_to 'Call on click', :onclick => check() %>
</h1>
我错过了,你在*链接字符串的构造过程中*打*检查。 –