Reputation: 2914
I am able to sort the users by their created_at
date by using @users.sort_by(&:created_at).reverse.each do |user|
I need help with sorting the subscribe users by the subscription created_at
date.
<% @users.each do |user| %>
<li>
<%= link_to user.username, user %>
<% if user.subscription %>
|<%= user.subscription.id %> | <%= user.subscription.plan.name %> | <%= user.subscription.created_at.strftime("%B %e, %Y") %> | <% if user.subscription.stripe_customer_token.nil? %> PAYPAL <% end %>
<% if user.subscription.paypal_recurring_profile_token.nil? %> STRIPE <% end %>
I think I need to change all of that code in the view, as I should really only be showing users that are inside the Subscription table. Instead I am pulling from the Users table, and then grabbing their subscription information. Current code is of course showing Users without subscriptions.
Upvotes: 0
Views: 46
Reputation: 5229
You can do it on controller action with something like this:
@users = User.includes(:suscription).order('subscriptions.created_at desc')
I hope it help.
Upvotes: 1
Reputation: 2691
You can achieve the desired outcome when you are querying database:
User.includes(:subscription).order("subscriptions.created_at DESC")
This query will eagerly load the subscription records for users, and will sort the records by subscription's created_at
field. If you are not already eagerly loading the subscription records using includes(:subscription)
, this approach will eliminate a lot of queries as it prevents your database to be hit each time you call user.subscription
in your code.
Upvotes: 1
Reputation: 2435
sort_by can take a block.
@users.sort_by {|user| user.subscription.created_at}
http://ruby-doc.org/core-2.1.3/Enumerable.html#method-i-sort_by
Just put it in the chain
@users.sort_by {|user| user.subscription.created_at}.reverse.each do |user|
This works assuming Subscription belongs_to User and User either has_one, or has_many Subscriptions. Which I can tell by your view it does.
Upvotes: 1