Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6618613
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T20:51:26+00:00 2026-05-25T20:51:26+00:00

I’m writing a simple membership application. I have two models, Member and Membership .

  • 0

I’m writing a simple membership application. I have two models, Member and Membership.

class Member < ActiveRecord::Base
   has_many :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :member
end

A member holds information like name and date of birth, a membership holds the date the membership was applied for, the date it started, the date it expires etc. Once a membership expires, the member can renew it, which creates a new membership. This means that each member can have multiple memberships, although only the latest will be their current, valid membership.

I now want to retrieve, for example, all members whose membership has expired. I can’t just do something like

@members = Member.joins(:memberships).where('memberships.expires < ?', Time.now) 

as this will include any current members who have had memberships in the past. What I really need to do is to be able to join to only the most recent of a member’s memberships and base the query on that. I’m new to Rails though so struggling a bit with this – help or ideas very much appreciated.

EDIT: Obviously this is the kind of thing that’s not difficult to do in plain old SQL, but I was hoping there’d be some nice Rails way to do it (other than just pasting the SQL in).

I would also rather not add another column to either of the tables just to make the queries I want to do possible. It’s messy, I shouldn’t have to do it, and will most likely cause problems down the line.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T20:51:26+00:00Added an answer on May 25, 2026 at 8:51 pm

    Thanks for all your suggestions. I’ve voted them up rather than accepting them as I don’t feel they quite cover what I want, but what I’m going to do has certainly benefitted from them.

    I still feel that SQL should be avoided if possible (for all the reasons I’ve already mentioned in comments), but I think in this case it can’t, so I’ve decided to define a named scope for the Member model like this:

    EDIT: I originally defined this as the default scope – however I have decided to heed the warning from KandadaBoggu on complex default scopes, so have made it a named scope instead. The query is also a bit more complicated than others described to cope with excluding renewed memberships (where the start date is in the future) when a currently active membership exists. Thanks again to KandadaBoggu for the bones of the query and hint on avoiding N+1 selects.

    scope :with_membership, lambda { 
    select('members.*, m.applied AS applied, m.paid AS paid, m.start AS start, m.expiry as expiry').
    joins("INNER JOIN (
      SELECT m3.*
      FROM memberships m3
      LEFT OUTER JOIN memberships m5 
      ON m3.member_id = m5.member_id 
      AND m5.created_at > m3.created_at
      AND m5.expiry > #{sanitize(Time.now)}
      WHERE m3.expiry > #{sanitize(Time.now)}
      AND m5.id IS NULL
      UNION
      SELECT m1.*
      FROM   memberships m1
      LEFT OUTER JOIN memberships m2 
      ON m1.member_id = m2.member_id 
      AND m2.created_at > m1.created_at 
      LEFT OUTER JOIN memberships m4 
      ON m1.member_id = m4.member_id 
      AND m4.expiry > #{sanitize(Time.now)}
      WHERE  m2.id IS NULL AND m4.id IS NULL
      ) m 
      on (m.member_id = members.id)") }         
    

    I’ve seen prettier bits of code. But my rationale is this – if you’re going to have to have a horrible bit of SQL like this, you might as well have it in only one place rather than repeated all over the place for every different query you might need (like expired members, members who haven’t paid yet etc etc).

    With the above scope in place, I can just treat the extra membership columns as normal columns on Member, and write nicely simple queries like this:

    #expired
    Member.with_membership.find :all, :conditions => ['expires < ?', Time.now ]
    
    #current
    Member.with_membership.find :all, :conditions => ['started < ? AND expires > ?', Time.now, Time.now ]
    
    #pending payment
    Member.with_membership.find :all, :conditions => ['applied < ? AND paid IS NULL', Time.now ]
    

    To briefly justify accepting my own answer rather than one of the other, very useful answers, I want to point out that this was never a question about how to get the ‘greatest n per group’ (although this is a component of it). It was about how to best deal with this kind of query in the specific environment of Rails, with the specific problem of members with multiple memberships where only one is active at any one time, and with a number of similar queries that all need fields from this single active membership.

    That’s why I think using a named scope in this way is, ultimately, the best answer to the question. Put up with the hideous SQL query, but have it in one place only.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
Thanks in advance for your help. I have a need within an application to
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a jquery bug and I've been looking for hours now, I can't
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.