0

I am new to ruby on rails. I am trying to retrieve data from my database and make operation in my rails application. I am stuck while trying to use find_by_sql in my class Activity < ActiveRecord::Base

I have a rates table with structure as

id | Instrument Name | Category | Time_of_usage | Rates
1  | Instrument1     | Internal | Regular       | 25
2  | Instrument2     | Internal | Weekends      | 15  

Here is my sample code of what I am trying to achieve

sql2='SELECT Rates FROM New_billcodes_mock WHERE Category_name=?, Instrument_name=? and Time_zone_name=?'
result2=  find_by_sql[sql2,'Internal','Instrument1',time_zone_name]
database_billrate_value_normal=result2['Rates']

and use the database_billrate_value_normal variable to make my operations.

Please guide me in the correct path if I am wrong.

Anil Pediredla
  • 704
  • 2
  • 8
  • 20

1 Answers1

0

I'm unclear if the model with the rate table is Activity or NewBillcodeMock or Rate.

If it is Rate, you should be able to do something like this:

database_billrate_value_normal = 
    Rate.where("category_name=? AND 
                instrument_name=? AND 
                time_zone_name=?",
                params[:category_name],
                params[:instrument_name],
                params[:time_zone_name]).pluck[:rates]

... assuming you have a hash params with the required attribute values those are the actual attribute names.

This will return an array of rates which you can then manipulate directly in Ruby as needed.

steve klein
  • 2,566
  • 1
  • 14
  • 27
  • The name of the table is New_billcodes_mock, the attribute values that I want to retrieve are Rates. If I were to use 'where' method what would be the class of the variable database_billrate_value_normal? – Anil Pediredla Jul 16 '15 at 20:30
  • Ruby utilizes [duck typing](http://rubylearning.com/satishtalim/duck_typing.html), so there is no need to type variables. You should also look into Rails naming conventions like [this one](http://edgeguides.rubyonrails.org/active_record_basics.html#naming-conventions) for Active Record and [this one](http://guides.rubyonrails.org/action_controller_overview.html#controller-naming-convention) for controllers. There are a number of other very good sources. Starting off with a fundamental knowledge of Rails conventions can save a lot of grief down the road. – steve klein Jul 16 '15 at 20:39
  • I have a table name 'Times' in my database, when I try to run query on it as result1=Times.where("id=?","1") I am getting an error message "NameError (uninitialized constant Activity::Times):" – Anil Pediredla Jul 17 '15 at 18:38
  • Is there a Times instance with `id` of 1? If so, you can use `Times.find(1)`. – steve klein Jul 17 '15 at 19:22