2016-02-13 40 views
1

我对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> 
+0

我错过了,你在*链接字符串的构造过程中*打*检查。 –

回答

0

如果你想从link_to调用一些途径试图

link_to "Call on click", controller: "articles", action: "check"

,然后只需添加路由get 'articles/check'

0

在你的点击函数中添加以下语句以防止控制器的操作被调用

function click(event){ 
    event.preventDefault(); 
    your previous app logic 
} 
0

在你routes.rb补充一点:

get '/articles/check' => 'articles#check', as: :check_article 

然后在你的观点,你应该做这样的事情:

<%= link_to "Check article", check_article_path, remote: true %> 

通知的remote:选项,它会告诉轨送请求通过ajax而不是加载一个新的页面(我假设这是预期的行为)。

现在,由于您通过ajax发送请求,因此Rails应该用一些javascript响应请求。请问是这样的在CoffeeScript中:

#views/articles/check.js.coffee 
$ -> 
    $("a[data-remote]").on "ajax:success", (e, data, status, xhr) -> 
    alert "Article was checked." 
0

你得到之间sever-side(Rails)的混淆& client-side(JS)事件。


考虑以下几点:

#config/routes.rb 
resources :articles do 
    get :check, on: :collection #-> url.com/articles/check 
end 

#app/controllers/articles_controller.rb 
class ArticlesController < ApplicationController 
    def check 
    # do something 
    end 
end 

以上将允许您使用...

<%= link_to "Check", articles_check_path %> 

这将触发每一个链接 “点击” 时,的确它会导致您的浏览器将您带到您尝试查看的新操作/视图。

以上是服务器端的功能。这是标准HTTP


你混淆了以上的JavaScript

#app/assets/javascripts/application.js 
var check = function() { 
    // do something 
} 

以上是客户端,并且只能用在JavaScript中onclick/.on("click"事件处理函数中调用:

<%= link_to "Check", some_path, onclick: "return check();" %> 

This是客户端,仅适用于加载到DOM中的元素。它通常用于为应用程序的前端提供额外的功能。