我将视图中的值(由用户输入)传递给控制器方法,该方法又从数据库中获取数据。以下是我认为的代码
<%= 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 %>
值 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 控制台上执行相同的查询时,它会给出结果。下面是来自 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">]
我已经对 DB 中存在的几乎所有值进行了很多尝试,但每次通过视图完成时都是相同的,并且在通过 rails 控制台执行查询时得到结果。在发帖之前我已经尝试了很多,因为我认为传递价值没有任何问题。只是选择查询不起作用。请指教。谢谢。