2012-07-31 70 views
0

我在Rails和ActiveRecord的工作,並試圖合併在一起,在我看來,從相關表的一些數據,這裏是我的模型:ActiveRecord的關係加入

class Report < ActiveRecord::Base 
    has_many :votes 
end 

class Vote < ActiveRecord::Base 
    belongs_to :reports 
end 

class User < ActiveRecord::Base 
    has_many :votes 
end 

每一票都有一個用戶和報告。

在我看來,我必須滿足下列條件,希望儘可能方便:

  1. 投票從所有用戶的每個報告總數
  2. 真/假,如果用戶已經投票的具體報告

現在,我的ActiveRecord查詢的基本的瞭解只需要我,只要有報告和當前user創建幫手和查詢比對existe的report

同樣NCE進入點票總數爲所有用戶提供一個report如下:

控制器

def index 
    #this is where I need some help to get the related information into a single 
    #object 
    @reports = Report.where('...') 
end 

查看

<% @reports.each do |report| %> 
    <% if(hasVoted(@current_user.id, report.id)) %> 
     <!-- display the 'has voted html' --> 
    <% end %> 
<% end %> 

幫手

def hasVoted(current_user_id, report_id) 
    if(Vote.exists?(:user_id => current_user_id, :report_id => report_id)) 
     true 
    else 
     false 
    end  
end 

希望能給你一些見解,幫助...謝謝!

回答

1

當然。

首先,請考慮命名您的方法has_voted?而不是hasVoted。其次,考慮在用戶模型中移動該方法。

#user.rb 
def voted_on?(report_id) 
    votes.where(:report_id => report_id).exists? 
end 

您的觀點將讀取

<% if current_user.voted_on?(report) %> 
    ... 
<% end %> 

你必須是找票的報告已收到的數量等問題。這也很簡單。在這裏你遍歷@reports

<% vote_count = report.votes.size %> 

請記住,他會導致N次查詢,你可以做到這一點在循環中您的視圖(其中N =報告數)。由於您是Rails的新手,我不會在控制器中將您的報告查詢複雜化,您可以在其中獲取報告以包含投票計數(除非您要求我提供)。但是,一旦你對這裏發生的事情感到滿意,那就是你要優化的地方。

+0

謝謝,那麼我需要在查詢中添加一個'include'子句嗎?或者ActiveRecord會根據'Reports'模型建立關聯關係? – 2012-07-31 06:08:11

+0

您不需要在查詢中包含投票。如果我們正在編寫一個更復雜的查詢,那麼一次性獲取報告信息和投票計數,我們將包括投票。 – 2012-07-31 06:11:07

+0

我做了一個'<%= debug report%>',看起來我在設置表格時沒有正確地建立關聯關係,我在'Vote'表格中手動添加了一個'report_id'列,一旦我正確地建立連接,我認爲你的ActiveRecord應該足夠聰明,只需通過查詢「Report」 – 2012-07-31 06:15:42