2016-04-21 88 views
0

首先,我想在Rails 4文件的視圖中實現一個簡單的單一輸入表單方法。在Rails 4中調用按鈕提交動作的方法

此表格需要在用戶提交後在表Points中創建新記錄。

要設置它,在我的homeform.html.erb中,我添加了一個帶post方法的鏈接來測試(following this answer)。

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

在我PagesController,我有一個相應的類:

class PagesController < ApplicationController 

    def points 

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

我通過創建有兩個硬編碼屬性的記錄,看看它的工作原理測試。最後,在我的的routes.rb文件,我說:

post 'points/promo_points' 

有了希望,當我點擊鏈接視圖後,這將執行promo_points方法和產生新的記錄。

這沒有發生,因爲我收到No route matches [POST] "/points"的錯誤。鑑於這種形式的簡單性,每當用戶點擊鏈接或提交時,是否有更簡單的方法從Rails中的表單助手調用promo_points方法?

回答

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

UPD:

def points 

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

通過這種方式,你只定義promo_points方法,但不調用它。

如果您移動promo_points方法Point類這將是很好的:

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

,並調用它在你的控制器:

class PagesController < ApplicationController 

    def points 
    Point.promo_points! 
    end 
end 
+0

頁面現在加載;但是,它不會使用我的頁面控制器中的方法使用'promo_points'動作。也許是因爲我們沒有專門調用它?爲了測試,我正在運行'Point.last',它不創建新的記錄。有任何想法嗎? – darkginger

+0

@darkginger更新了我的答案 – zolter