Question

I am Learning ruby. I would like to use active record to use a simple find command like this: MyModel.find_by_emp_id(i.emp_id) on the model but I cant with the Vertica database gem I am using. The resultset of running a straight SQL query on the model like this: vemployees = conn.query("select * from employees") returns a hash like data structure. The data structure vemployees is a Vertica::result type, and the structure looks to be like bellow:

[
  {:emp_id=>"3321", :emp_last_name=>"Man", :emp_first_name=>"super", :emp_mid_name=>nil}, 
  {:emp_id=>"3325", :emp_last_name=>"Man", :emp_first_name=>"Bat", :emp_mid_name=>nil},
]

How can I execute something like, vemployees.find_by_emp_id(i.emp_id) without going through a list of results?

Was it helpful?

Solution

N.B. untested code

something like:

in MyModel:

def self.find_by_emp_id(id)
  conn.query("select * from employees where emp_id = #{id}")[0]
end

Since the gem is not ActiveRecord you'll have to write your own accessors, you cannot rely on the automagically created ActiveRecord find_by_ methods. I think you can hack that gem into ActiveRecord and have all of ActiveRecord's goodness but that's probably more than you'd want to take on as a Ruby beginner.

Be careful to sanitize any user input ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top