0

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?

Community
  • 1
  • 1
darkginger
  • 652
  • 1
  • 10
  • 38

1 Answers1

1
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
zolter
  • 7,070
  • 3
  • 37
  • 51
  • The page now loads; however, it does not post using the `promo_points` action from the method in my Pages Controller. Maybe it's because we are not calling it specifically? To test, I am running `Point.last` and it's not creating a new record. Any ideas? – darkginger Apr 22 '16 at 00:35
  • @darkginger Updated my answer – zolter Apr 22 '16 at 06:42