从Rails 4

时间:2016-04-21 08:08:00

标签: ruby-on-rails ruby forms

首先,我想在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 个答案:

答案 0 :(得分: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