Jeff Zivkovic
Jeff Zivkovic

Reputation: 587

Rails query using dynamic column

I've got this method that's working fine. But it feels like an opportunity for me to improve my Ruby skills.

In my app, students can be given bucks for a specific seminar, or for their whole school. When it comes time to total up how many bucks a student has received, I run this method.

def bucks_owned(category, source)
    if category == "giver"
        return self.currencies.where(:giver => source).sum(:amount)
    else
        return self.currencies.where(:school => source).sum(:amount)
    end
end

It seems like Ruby would allow for a dynamic column in the query. I've tried this, but it didn't work as I hoped.

def bucks_owned(category, source)
    self.currencies.where(:"#{category}" => source).sum(:amount)
end

Upvotes: 0

Views: 712

Answers (1)

Ursus
Ursus

Reputation: 30056

Have you tried this one?

def bucks_owned(category, source)
  self.currencies.where(category => source).sum(:amount)
end

Upvotes: 2

Related Questions