2012-10-03 71 views
0

我有兩個模型,我試圖在索引視圖中顯示一個用戶的學分。Ruby on Rails用戶總學分

class User < ActiveRecord::Base 
has_many :credits 



class Credit < ActiveRecord::Base 
belongs_to :user 

我想在index.html.erb視圖中顯示用戶的總積分。我創建了一個輔助方法。

module UsersHelper 

def designer_owed 
    designer_owed = Credit.where(:user_id => @user).sum(:total_received) 
    end 

我得到的結果有點混亂,我知道我做錯了什麼,但我無法弄清楚。

index.html.erb

<%= h number_to_currency(designer_owed, :unit => "$") %> 

我得到一個零。

但我show.html.erb

<%= H number_to_currency(designer_owed,:單位=> 「$」)%>

我得到正確的總。我的SQL看起來像這樣,當我查詢使用index.html.erb

SELECT SUM("credits"."total_received") AS sum_id FROM "credits" WHERE "credits"."user_id" IS NULL 

我想顯示在索引視圖。

回答

1
def index 
    @users = User.includes(:credits) #fires 2 queries. for users and for credits. use for code optimization 
end 
鑑於

,做

%table 
    %thead 
    %tr 
     %th User 
     %th Credits 
    %tbody 
    - @users.each do |user| 
     %tr 
     %td user.name 
     %td user.credits.collect(&:total_recieved).sum #doesnt fire extra query cause we have used 'includes' 

結賬http://guides.rubyonrails.org/active_record_querying.html

+0

由於它的工作。 – Benjamin

1

在您的視圖中,像'@user'這樣的實例變量對應於控制器中的實例變量。

在您的索引控制器和相應的視圖中,通常會有一個包含所有用戶的「@users」實例變量。事實上,在許多情況下,索引操作可以簡單:

def index 
    @users = User.all 
end 

在任何情況下,這將是不尋常的索引內的@user變量 - 它似乎不這樣做,因此你得到的錯誤。

在索引視圖,我想你想通過所有用戶進行迭代,並顯示欠各量,使:

<%= h @users.each {|user| number_to_currency(designer_owed(user), :unit => "$") %> 

我再培訓局是有點生疏,因爲我一直在使用Haml的進行過現在年齡,但我認爲這應該工作。你會想改變它來滿足你的佈局需求。

您的輔助方法,現在只需在一個用戶的說法:

def designer_owed(user) 
    Credit.where(:user => user).sum(:total_received) 
end