DDDD
DDDD

Reputation: 3940

Query column for duplicate from variable

I want to check if a string already exists in a table column. The column name is in the form of a string, @language = 'german', column name being german.

Word.where(@language: string).empty?

So I want it to do

Word.where(german: string).empty?

How can I use @language in the where clause?

Upvotes: 0

Views: 63

Answers (4)

kddeisz
kddeisz

Reputation: 5202

You could use exists?:

Word.exists?(@language => string)

The issue you're having is that the syntax @language: string actually means :@language => string.

Don't think this is going to be slower:

require 'benchmark'    
@language = 'english'
string = 'Hello world'

Benchmark.bm do |x|
  x.report { 100000.times { a = Hash[@language, string] } }
  x.report { 100000.times { a = { @language => string } } }
end

prints out

    user     system      total        real
0.100000   0.040000   0.140000 (  0.143954)
0.050000   0.000000   0.050000 (  0.050434)

on my machine.

Interestingly enough, on my machine it looks like .where().exists? is faster than .exists? on its own:

require 'benchmark'
column = 'last_name'
value = 'Jones'

Benchmark.bm do |x|
  x.report { 10000.times { User.exists?(column => value) } }
  x.report { 10000.times { User.where(column => value).exists? } }
end

Upvotes: 2

Ravindra
Ravindra

Reputation: 150

You could use column_names return all table column field name

Word.column_names.include?(@language)

Upvotes: 0

max
max

Reputation: 102443

Word.where(Hash[@language, string]).exists?

Hash[@language, string] is one of those beautiful rubyisms that creates a hash dynamically.

irb(main):005:0> @language = 'german'
=> "german"
irb(main):006:0> string = 'kummerspeck'
=> "kummerspeck"
irb(main):007:0> Hash[@language, string]
=> {"german"=>"kummerspeck"}

Upvotes: 2

penner
penner

Reputation: 2737

Might vary based on db, dynamic columns not recommended btw

Word.where("#{@langauge} IS NULL")

Upvotes: 1

Related Questions