将视图中的参数传递给控制器​​。然后回到视图

时间:2015-01-07 19:13:41

标签: ruby-on-rails ruby forms ruby-on-rails-4 parameter-passing

目标是从表单中捕获输入,然后在控制器和服务完成后,将结果显示在另一个视图上。主要问题是控制器和表单视图之间的交互。视图应将捕获的输入作为参数传递给控制器​​并继续其快乐方式。如何正确捕获参数并将其传递给控制器​​?

# controller
class CheckNumberController < ApplicationController
  require_relative '../services/number_check_modulo'
  def get_cert_number(cert)
    @cert_id = cert
  end

  def show_check_number
    checking_policy_number = Get_policy_check_digit.new(@cert_id) # Creates a new instance of the "Get_policy_check_digit" class
                                                                 # From number_check.rb
    @check_number = checking_policy_number.create_check_digit     # Runs the "create_check_digit" method from the "Get_policy_check_digit" class
  end
end

# service 'app/services/number_check_modulo' required in the controller shown above
class Get_policy_check_digit
  def initialize(cert_id)
    #instance variable
    @cert = cert_id
  end

  def create_check_digit
    cert_id_6 = @cert.to_s
    cert_id_6.slice!(0)
    cert_id_6.to_i
    cert_id_6 % 7
  end
end

我目前在视图中使用表单助手form_tag。用户提交号码后,页面将重定向到输出显示页面。

# Form view
<H1>Enter Cert Number below</H1>

<%= form_tag('show_check_number', method: 'get') do %>
    <%= text_field_tag(:cert) %>
    <%= submit_tag("Submit") %>
<% end %>

此页面仅显示服务'app / services / number_check_modulo'所做计算的结果

# View that shows the result
<h1>Your check number is <%= @check_number %></h1>

我对此很新,但我认为我走的正确。

2 个答案:

答案 0 :(得分:2)

尝试将方法show_check_number更改为此

def show_check_number
  checking_policy_number = Get_policy_check_digit.new(params[:cert]) 
  @check_number = checking_policy_number.create_check_digit    
end

答案 1 :(得分:1)

我建议你这个重构:

# controller
require 'app/services/number_check_modulo'    
class CheckNumberController < ApplicationController

  def show_check_number
    policy_check_digit = PolicyCheckDigit.new(params[:cert])
    @check_number = policy_check_digit.create_check_digit
  end
end

# app/services/number_check_modulo
class PolicyCheckDigit
  def initialize(cert_id)
    @cert = cert_id
  end

  def create_check_digit
    cert_id_6 = @cert.to_s
    cert_id_6.slice!(0)
    cert_id_6.to_i
    cert_id_6 % 7
  end
end