2012-12-27 33 views
0

我試圖在我的管理區域中顯示特定用戶的帳單詳細信息。我想要做的只是將用戶標識輸入到文本字段中,然後按提交,鏈接到該用戶標識的帳單將顯示在下表中。這裏是我的CAC遞給努力迄今:試圖在特定用戶的表格中顯示結果user_id

管理/ index.html.erb

<%= form_tag(:action => "show_billings") do %> 
<div class="field"> 
    <p>User ID</p> 
    <%= text_field_tag :user_id %> 
</div> 
<div class="actions"> 
    <%= submit_tag "Show Billing For This User", :class => 'btn btn-success' %> 
</div> 
<% end %> 

<table class="table table-hover table-striped table-bordered"> 

<thead style="background-color: #efefef"> 

<tr> 
<th>Date</th> 
<th>Description</th> 
<th>Debits</th> 
<th>Credits</th> 
<th>Balance</th> 
</tr> 

</thead> 

<tbody> 

<% @billings.each do |billing| %> 
    <tr> 
    <td><%= billing.date %></td> 
    <td><%= billing.description %></td> 
    <td><%= number_to_currency(billing.debits) %></td> 
    <td><%= number_to_currency(billing.credits) %></td> 
    <td><%= number_to_currency(billing.balance) %></td> 

    </tr> 
<% end %> 
</tbody> 
</table> 

admin_controller.rb

def show_billings 
    billings = Billing.where(:user_id => params[:user_id]) 
    if billings.nil? 
     @billings = Billing.where(:user_id => '22') 
    else 
     @billings = billings 
    end 
    end 

我得到了下面的錯誤,這就是爲什麼我試圖使@billings不是零:

undefined method `each' for nil:NilClass 

我不知道def show_billings是否是必要的,仍然是非常新的軌道a nd我做的所有事情總是錯的,所以這可能也是,我該如何解決?

回答

1

嗯,您是否從index行動中致電show_billings?您向我們展示在index操作後呈現的index.html.erb。該表格確實發佈到show_billings,但通常會顯示show_billing.html.erb

因此,無論是寫在你的index.html.erb,如@billings = [],所以你不會得到一個錯誤,並讓show_billings呈現與索引相同的視圖。但是,我甚至沒有看到真正需要單獨採取行動:讓搜索表單再次進入索引?無論如何,這是相同的代碼。

+0

是的,它是從索引行動,抱歉不包括。我如何讓搜索表單再次進入索引?我在def show_billings中加入了redirect_to:action =>'index',但是當我將user_id添加到:user_id字段時,該表不會更新。這太令人沮喪了,因此基於user_id顯示簡單表格對我來說很難。我們甚至需要def show_billings還是有更好的方法來做到這一點? – railsy

+0

您的索引操作看起來如何?如果你寫'form_tag'沒有參數,它會回到'form_tag:action => index'的索引。所以不需要show_billings。理想情況下,您將如何執行此操作:使用'admin/users'並點擊用戶以轉到'admin/users /:id'查看用戶帳單。更接近軌道。在單個用戶的展示視圖中,我將顯示一個包含所有用戶的下拉框以方便切換。祝你好運。 – nathanvda

+0

好的非常感謝您的幫助,至少得到它的工作,將嘗試您建議的更改 – railsy

1
def show_billings 
    if params[:user_id] 
     @billings = Billing.where(:user_id => params[:user_id]) 
    else 
     @billings = Billing.where(:user_id => '22') 
end 

讓我知道你是如何得到的。

+0

謝謝,但仍然給我同樣的錯誤:未定義的方法'each'爲零:NilClass – railsy

+0

嘗試@billings = Billing.find(:all)查看數組中的內容並縮小到您需要的範圍? – hd1

+0

@ billings在def show_billings中並沒有被拿起,我在@ billings = Billing.all中加入了它,並且仍然得到了零:NilClass錯誤(必須在@符號後添加一個空格以避開SO評論規則思維我試圖通知某人叫billings) – railsy

相關問題