如何将特定控制器操作路由到rails中的特定表单?

时间:2015-09-07 06:24:34

标签: ruby-on-rails

嗨,我是RoR的新手,我正在制作一个简单的math_app。添加功能正常。现在我尝试进行简单的减法。调用减法控制器并显示减法形式,但是当我点击减去时,调用添加控制器并执行添加。我哪里出错?

这是我的routes.rb

Rails.application.routes.draw do
  get 'subtract/form'

  post 'subtract/result'

  get 'add/form'

  post 'add/result'
end

result.html.erb

<%= @first %> - <%= @second %> = <%= @result %>
<br/>
<%= link_to 'back', subtract_form_path %>

form.html.erb :(这是减法表格)

<%= form_tag subtract_result_path do %>
  <%= number_field_tag :first %>
 -
  <%= number_field_tag :second %>
  <%= submit_tag "subtract" %>
<% end %>

subtract_controller.rb

class SubtractController < ApplicationController
  def form
  end

    def result
        @first = params[:first].to_i
        @second = params[:second].to_i
        @result = @first - @second
    end
end

1 个答案:

答案 0 :(得分:0)

views/substract/form.html.erb有问题。它现在写着:

<%= form_tag add_result_path do %>
  <%= number_field_tag :first %>
 -
  <%= number_field_tag :second %>
  <%= submit_tag "subtract" %>
<% end %>

但它应该是:

<%= form_tag substract_result_path do %>
  <%= number_field_tag :first %>
 -
  <%= number_field_tag :second %>
  <%= submit_tag "subtract" %>
<% end %>

您可能还应该修复路线

post '/subtract/result' => 'subtract#result', as: 'substract_result'

同样在views/substract/result.html.erb

<%= @first %> - <%= @second %> = <%= @result %>
<br/>
<%= link_to 'back', subtract_form_path %>