简体   繁体   English

在rails helper方法where()查询中使用变量列名

[英]Using a variable column name in a rails helper method where( ) query

I'm working with a User model that includes booleans for 6 days 我正在使用一个包含布尔值的用户模型长达6天

[sun20, mon21, tue22, wed23, thur24, fri25]

with each user having option to confirm which of the 6 days they are participating in. 每个用户可以选择确认他们参加的6天中的哪一天。

I'm trying to define a simple helper method: 我正在尝试定义一个简单的辅助方法:

  def day_confirmed(day)
    User.where(day: true).count
  end

where I could pass in a day and find out how many users are confirmed for that day, like so: 我可以在哪一天过去,并确定当天确认了多少用户,例如:

day_confirmed('mon21')

My problem is that when I use day in the where() , rails assumes that I'm searching for a column named day instead of outputting the value that I'm passing in to my method. 我的问题是,当我在where()使用day时,rails假设我正在搜索名为day的列,而不是输出传递给我的方法的值。

Surely I'm forgetting something, right? 我肯定会忘记一些东西,对吧?

This syntax: 这个语法:

User.where( day: true )

Is equivalent to: 等效于:

User.where( :day => true )

That's because using : in a hash instead of => , eg { foo: bar } , is the same as using a symbol for the key, eg { :foo => bar } . 这是因为在哈希中使用:而不是=> (例如{ foo: bar } )与在键中使用符号(例如{ :foo => bar } Perhaps this will help: 也许这会有所帮助:

foo = "I am a key"

hsh = { foo: "bar" }
# => { :foo => "bar" }

hsh.keys
# => [ :foo ]

hsh = { foo => "bar" }
# => { "I am a key" => "bar" }

hsh.keys
# => [ "I am a key" ]

So, if you want to use the value of the variable day rather than the symbol :day as the key, try this instead: 因此,如果要使用变量day的值而不是符号:day作为键,请尝试以下方法:

User.where( day => true )

If these are your column names, [sun20, mon21, tue22, wed23, thur24, fri25] 如果这些是您的列名, [sun20, mon21, tue22, wed23, thur24, fri25]

And you are calling day_confirmed('mon21') and trying to find the column 'mon21' where it is true , you can use .to_sym on the date variable 您在调用day_confirmed('mon21')并试图找到列“mon21”它是true ,你可以使用.to_sym上的date变量

 def day_confirmed(day)
    User.where(day.to_sym => true).count
  end

the .to_sym will get the value of date , and covert it to :mon21 .to_sym将获取date的值,并将其转换为:mon21

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

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