1

I have the fallowing entities:

User has_many Projects

Project has_many ProjectKeywords

Keyword has_many ProjectKeywords

Project and Keyword has_many Reports

I want to display a data chart in one of my pages, but I don't know how to display the reports for the Projects owned by a User. This is how I display my rows from Result table right now.

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

end

4

1 回答 1

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
于 2013-10-30T14:29:16.890 回答