没有数据库的模型:未初始化的常量

时间:2013-10-27 03:33:31

标签: ruby-on-rails ruby-on-rails-4 rails-routing activemodel

我在轨道上的红宝石中很安静。我正在尝试开发一个仅在控制器中使用ActiveModel对象而不保存的应用程序。不幸的是,点击提交按钮后,我收到一个错误。此应用程序的目的是执行一些计算并显示结果。我怎样才能做到这一点?

路由错误 没有路线匹配[POST]“/ shugarcalc”

app / models / sugar_amount.rb

    class SugarAmount   
      include ActiveModel::Model  

      attr_accessor :l, :h, :b, :tw, :tf  

      VALID_NUMBER_REGEX= /[0-9]{1,2}([,][0-9]{1,2})?/  

      validates :l, presence: true, format: { with: VALID_NUMBER_REGEX },  length: { maximum: 10 }  
      validates :h, presence: true, format: { with: VALID_NUMBER_REGEX },  length: { maximum: 10 }  

    end  

config / routes.rb

    SimpleDesign::Application.routes.draw do  
      root 'static_pages#home'  

      resources :sugar_amount, only: [:new, :create]  

      match '/shugarcalc',  to: 'shugar_amounts#shugar',            via: 'get'    

    end  

app / controllers / shugar_amounts_controller.rb

    class ShugarAmountsController < ApplicationController  

      def sugar  

        @sugar_amount=SugarAmount.new  

      end  

      def create    
        @sugar_amount = SugarAmount.new(params[:sugar_amount])    
        /here i want to use some functions /       
        redirect_to root_url      
        /this is temporary, just to see if anything happens  /      

      end  

    end  

app / views / sugar_amounts / sugar.html.erb

    <%= form_for(@sugar_amount) do |f| %>  

      <%= f.label :l, "eggs" %>  
      <%= f.text_field :l %><br>  

      <%= f.label :h, "flour [mm]" %>  
      <%= f.text_field :h %><br>  

      <%= f.submit "Reduce!" %>  
    <% end %>

1 个答案:

答案 0 :(得分:1)

您的错误消息:

  

路由错误没有路由匹配[POST]“/ shugarcalc”

表示您正在对/shugarcalc进行POST。但是你的路线是为GET请求定义的:

match '/shugarcalc',  to: 'shugar_amounts#shugar',            via: 'get'
# ------------------------------------------------------------^^^^^^^^^^

所以对/shugarcalc的POST不起作用。此外,该路由将查找ShugarAmountsController#shugar但您在该控制器中没有shugar方法。

首先确定/shugarcalc是否应该是GET或POST(提示:如果它只是进行一些计算并返回结果而不修改任何内容然后它可能是GET)然后调整路径{{1选项或您如何尝试相应地访问路线。然后将via:方法添加到shugar

我还建议您正确拼写“糖”。有时将它作为“shugar”,有时候“糖”会让你疯狂,试图记住在哪个地方使用哪种拼写,并且可能会与Rails喜欢的假设产生一些冲突。