从控制器中的视图传递值

时间:2013-09-05 10:36:47

标签: ruby-on-rails ruby-on-rails-3

我将视图中的值(由用户输入)传递给控制器​​方法,控制器方法又从数据库中获取数据。以下是我视图中的代码

<%= form_tag({:controller=>"billings", :action=>"tablebill"}, method: :get) do %>
  <div class="center-data">Table Number:
    <div class="tinput"> <%= text_field_tag(:tableno) %></div>
  </div>
  <div class="ebutton">
    <%= submit_tag "Enter" %>
  </div>
<% end %>

Value tableno是我在控制器方法中需要的,编码如下

def tablebill
  @orders = List
   .select("itemname,tableno,quantity,amount")
   .where(:tableno => params[:tableno]).to_a

  @orders.each do |order|
    @totamount = @totamount + order.amount
  end

  @tax = @totamount/5
  @finalamount = @totamount + @tax

  respond_to do |format|
    format.html # tablebill.html.erb
  end  
end

该值在查询中成功传递,但返回的值为nil。以下是我服务器的片段

Started GET "/billings/tablebill?utf8=%E2%9C%93&tableno=08&commit=Enter" for 127
.0.0.1 at 2013-09-05 15:50:01 +0530
  Processing by BillingsController#tablebill as HTML
  Parameters: {"utf8"=>"√", "tableno"=>"08", "commit"=>"Enter"}
  List Load (1.0ms)  SELECT itemname,tableno,quantity,amount FROM `lists` WHERE
`lists`.`tableno` = '08'
Completed 500 Internal Server Error in 230ms

NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+):
  app/controllers/billings_controller.rb:8:in `block in tablebill'
  app/controllers/billings_controller.rb:7:in `each'
  app/controllers/billings_controller.rb:7:in `tablebill'

问题是当我在rails console上执行相同的查询时,它会给出结果。以下是rails控制台的片段

irb(main):073:0> @orders = List.select("itemname,tableno,quantity,amount").where(:tableno => '08')
=> [#<List tableno: "08", itemname: "test81 ", quantity: "1", amount: "
3.25">, #<List tableno: "08", itemname: "Test82", quantity: "1", amou
nt: "3.75">, #<List tableno: "08", itemname: "Test83", quantity: "1
", amount: "3.75">]

我已经尝试了很多数据库中存在的几乎所有值,但每次通过视图完成相同时,我通过rails控制台执行查询时得到结果。我在发布之前已经尝试了很多,因为我认为传递价值没有任何问题。它只是选择查询不起作用。请指教。感谢。

1 个答案:

答案 0 :(得分:1)

我认为这不是因为params[:tableno]是零,我认为这是因为你没有初始化@totamount。然后,当您尝试向其添加第一个order.amount时,您收到错误,因为您无法添加到nil

尝试在循环之前设置@totamount = 0或执行以下操作:

@totamount = order.map(&:amount).inject(&:+)

将所有金额加在一起。