vendredi 12 février 2016

Using link_to to only call a function in rails when the link is clicked

I'm very new to rails. I'm trying to call a function check() only when a link is clicked, but the controller will also call the function every time the view loads.

Routes: routes.rb

Rails.application.routes.draw do
  get 'welcome/index'

  resources :articles

Controller: 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

Model: article.rb

class Article < ActiveRecord::Base

end

View: index.html.erb

<h1>
  <%= link_to 'Call on click', :onclick => check() %> 
</h1>

Aucun commentaire:

Enregistrer un commentaire