darkginger
darkginger

Reputation: 690

Calling a method from a button submit action in Rails 4

First, I want to implement a simple, single input form method in the view of a Rails 4 file.

This form will need to create a new record in a table called Points after the user submits.

To set this up, in my homeform.html.erb, I have added a link with a post method to test (following this answer).

<%= link_to 'Call Action', points_path, method: :post %>

In my PagesController, I have a corresponding Points class:

class PagesController < ApplicationController

  def points

    def promo_points
      Point.create(user_id: 10, points: 500)
    end 
  end 
end

I am testing by creating a record with two hard coded attributes to see if it works. Finally, in my Routes.rb file, I added:

  post 'points/promo_points'

With the hope that when I click the link to post in the view, this will execute the promo_points method and generate that new record.

That is not happening, as I am receiving an error for No route matches [POST] "/points". Given the simplicity of this form, is there an easier way to call the promo_points method from the form helper in Rails every time the user clicks the link or submits?

Upvotes: 0

Views: 1746

Answers (1)

zolter
zolter

Reputation: 7160

post '/points', to: 'pages#points', as: :points

UPD:

  def points

    def promo_points
      Point.create(user_id: 10, points: 500)
    end 
  end

By this way you only define promo_points method but does not call it.

It will be good if you move your promo_points method to Point class:

class Point < ActiveRecord::Base
  def self.promo_points!
    create(user_id: 10, points: 500)
  end
end

And call it in your controller:

class PagesController < ApplicationController

  def points
    Point.promo_points!
  end 
end

Upvotes: 1

Related Questions