简体   繁体   中英

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

Have you tried this one?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM