2011-06-13 3 views
0

나는 Relationships 클래스가 있는데, 특정 날짜 범위 (현재와 4 주 전)에 몇 명의 친구가 있었는지에 대한 목록을 뱉어보고 싶습니다.루비에서 특정 created_at 날짜까지 어떻게 계산합니까?

은 내가 html.erb에서 다음을 시도했지만 그것은 작동하지 않는 것 :

<table> 
<% rightnow = DateTime.now.to_i %> 
<% twentyeight = Time.at(rightnow).to_time - 28.days %> 
<% twght = twentyeight.to_i %> 
<% (twght..rightnow).step(1.day).map do |time| %> 
    <tr><th><%= Time.at(time).strftime("%a %b %y") %></th></tr> 
    <tr><td><%= Relationship.where(:follower_id => @user.id, :created_at => from .. to time).count %></td></tr> 
</table> 

내가 대답이 하나의 라인을 따라 수 있습니다 의심하지만 난 몰라 그것을 구현하는 방법 ... Ruby count items by date

또한 MVC와 여전히 씨름 중이므로 어떻게 코드를 정리할 수 있습니까? 내 users_controller 메서드를 만들려고했지만 성공적으로 호출 할 수 없습니다.

건배.

편집 :

여기에 또 다른 시도가 있습니다. 피드백 오신 걸 환영 할 (+ 28 일 전)

<tfoot> 
<% before = DateTime.now - 28.days%> 
<% following = Relationship.where(:followed_id => @user.id) %> 
<tr> 
<% before.step(before + 28, 1) do |time| %> 
<th><%= time.strftime("%a %b #{time.day.ordinalize}") %></th> 
<% end %> 

<%의 before.step | 시간 | %> 아마

<td> 
<%= following.all(:conditions => ["created_at < ?", time.end_of_day]).count %> 
</td><% end %> 
</tr> 
</tbody> 
</table> 

답변

1

나는 우리가 튀어 나오는 부분을 건너 뛸 것입니다. '왜?' 스택. 자, 인수를 위해서 Relationships 컨트롤러의 인덱스 뷰를보고 있다고 가정 해 봅시다. 그 코드의 대부분은 컨트롤러에 속한, 그래서 쉬운 경우 시작하자 :

class RelationshipsController < ApplicationController 
    before_filter :set_user #whatever you do to load your currently logged in user 
    def index 
    @relationships = @user.relationships.where(:created_at => 28.days.ago..Date.today) 
    end 
end 

을보기에이 당신이 지난 28 일에 만들어 얼마나 많은 관계가 표시됩니다

<table> 
    <tr><th><%= Time.at(time).strftime("%a %b %y") %></th></tr> 
    <tr><td><%= @relationships.count %></td></tr> 
</table> 

. 이것은 비록 실행중인 집계에 당신을 얻을, 그래서 모델에 메서드를 추가하여 이제 디자인을 약간 리팩토링하지 않습니다

class Relationship < ActiveRecord::Base 
    #... skip other stuff 
    def self.relationship_count_for_days(start_date, end_date) 
    where(:created_at => start_date..end_date).count 
    end 
end 

다음보기가 될 것입니다 :

<table> 
    <% 28.downto(1) do |days_ago| %> 
    <tr><th><%= days_ago.days.ago.to_time.strftime("%a %b %y") %></th></tr> 
    <tr><td><%= @relationships.relationship_count_for_days(28.days.ago, days_ago.days.ago) %></td></tr> 
    <% end 
</table> 
+0

건배 @karmajunkie 및 보리스. 나는 그것을 지금 시도 할 것이다. 그동안, 나는 MVC가 아닌 다른 솔루션을 제안했다. 내 의견을 나에게 줄 수 있다면 제 질문에 편집했습니다. – Ribena

+0

감사합니다. 코드 버전을 구현했으며 잘 작동합니다. 하지만 나는 내 편집물에 게시 된 코드보다 더 많은 쿼리를 받고 있다고 생각합니다. 코드로 쿼리 수를 줄이는 방법이 있습니까? – Ribena

+0

당신이 실제로 구현하고있는 것을보아야 하겠지만 내 충고는 쿼리에 대해 너무 걱정하지 않아야합니다. 병목 현상이되면 문제를 해결하십시오.그것은 새로운 레일 devs들이 머리를 감싸는 것이 일반적으로 어려운 일이며, 그럴 필요가 없지만 중요한 것들을 최적화 할 이유가 없습니다. 예를 들어, 이것은 처음에는 몇 가지 추가 쿼리를 실행할 수있는 캐시 가능보기이지만 캐시가 만료되거나 무효화 될 때까지 매번 0이 실행됩니다. – karmajunkie

1

당신이 다음에 무엇을 시도해야 : 컨트롤러에서
을 : 다음보기에서 프레젠테이션을 @relationships을 반복하고 builld 수

@relationships = Relationship.where("created_at BETWEEN ? AND ?", your_start_date, your_end_date) 

* your_start_date - 될 수 있습니다 Time.now - 28.days

관련 문제