2013-10-30 73 views
1

數據我有休耕實體:獲得通過協會

User has_many Projects

Project has_many ProjectKeywords

Keyword has_many ProjectKeywords

Project and Keyword has_many Reports

我想在我的一個網頁顯示數據圖表,但我不知道如何顯示reportsProjects擁有User。這就是我現在如何從Result表中顯示我的行。

Reports controller:

def self.chart_data(start = 1.weeks.ago) 
    total_possitions = possition_by_day(start) 
    possitions_top_fiftys = where("possition < ?", 50).possition_by_day(start) 
    (start.to_date..Date.today).map do |date| 
    { 
    created_at: date, 
    possitions_top_fifty: possitions_top_fiftys[date] || 0, 
    } 
    end 
end 

def self.possition_by_day(start) 
    results = unscoped.where(created_at: start.beginning_of_day..Time.zone.now) 
    results = results.group("date(created_at)") 
    results = results.order("date(created_at)") 
    results = results.select("date(created_at) as created_at, count(*) as count") 
    results.each_with_object({}) do |result, possitions| 
    possitions[result.created_at.to_date] = result.count 
    end 

+1

你試過了嗎?user_projects = Project.where(「user_id =?」,current_user)'然後是'user_projects.first.reports'?你可能需要改變'current_user',但是類似的東西也應該工作 – dax

+0

,你是否使用rails 3或rails 4?你不能同時擁有... – dax

+0

我正在使用,導軌4和謝謝你 – John

回答

1

reports_controller

before_filter :user_projects 

#to find reports for a specific project 
def project_reports(project) 
    this_project = @user_projects.where("id = ?", project.id) 
    this_project.reports 
end 

def user_projects 
    @user_projects = Project.where("user_id = ?", current_user) 
end 

在你view

<%= @report.project_reports(@project) %> 
#=> reports associated with this user's specific project 

<% @user_projects.each do |project| %> 
    <% project.reports.each do |report| 
    <%= #report stuff here %> 
    <% end %> 
<% end %> 
#=> loops through each of the user's projects and shows the report how you wish