简体   繁体   English

使用动态列进行Rails查询

[英]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. 但这对我来说是提高我的Ruby技能的机会。

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. 看起来Ruby会允许在查询中添加动态列。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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