Hi all,

I have the following data columns in my table:

occurred_at, name
2012-01-01, Ryan
2012-01-01, Ryan
2012-01-01, Mark
2012-01-01, Ryan
2012-01-01, Paul
2012-01-01, John
2012-02-01, Ryan
2012-02-01, Mark
2012-02-01, Ryan
2012-02-01, Mark
2012-02-01, Paul
2012-02-01, Kevin
2012-03-01, Ryan
2012-03-01, Gary
2012-03-01, Ryan
2012-03-01, Mark
2012-03-01, Paul
2012-03-01, Kevin

What I'm trying to do is Group the names by date and add a count and
output this to a json

{ date: 2012-01-01, ryan: 3, mark: 1, paul: 1, john: 1 }

I have the following code so far:

# user controller
 def index
  @users = User.show_data
  render :json
end

# user model

def self.show_data(start = 14.months.ago)
    total_users = users_by_month(start)
    (start.to_date..Date.today).map do |date|
      {
        occurred_at: date,
        total_users[date].name.to_sym: total_users[count],
      }
    end
  end

def self.users_by_month(start)
    users = where(occurred_at: start.beginning_of_day..Time.zone.now )
    users = users.group("date(occurred_at)")
    users = orders.select("occurred_at, count(name) as user_name")
    users.each_with_object({}) do |user, names|
       names[user.occurred_at.to_date] = user.user_name
    end
  end

Thanks in advance,

Ryan

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to