how to get single latest record from a view and test it in console - ruby

I kinda have 2 questions. I have following model and method to get the latest record from view. but when i try to test in console i get error undefined method or variable vCustomerDetails why i am getting the error?
Also, how do i select only one column from view?
SELECT TOP 1 HasConditionFlag FROM vCustomerDetails
WHERE vCustomerDetails.UserID = #user_id
ORDER BY EntryDate DESC
Model
module Customer
class CustomerUsage < ActiveRecord::Base
self.table_name = 'vCustomerDetails'
def self.has_condition_flag(user_id)
vCustomerDetails
.where("vCustomerDetails.UserID = #{user_id}")
.order('vCustomerDetails.EntryDate DESC')
.last
end
end
end

this one worked
def self.has_condition_flag(user_id)
CustomerUsage
.select("vCustomerDetails.HasConditionFlag")
.where("vCustomerDetails.UserID = #{user_id}")
.order('vCustomerDetails.EntryDate DESC')
.first

Remove vCustomerDetails
module Customer
class CustomerUsage < ActiveRecord::Base
self.table_name = 'vCustomerDetails'
def self.has_condition_flag(user_id)
where("vCustomerDetails.UserID = #{user_id}")
.order('vCustomerDetails.EntryDate DESC')
.last
end
end
end
to select a limited number of columns use
.select('HasConditionFlag')

Related

Comparing time for nested associations

I'm in the process of building an application that'll accept a specific date from a user and which will then provide a list of events that have occurred prior to that date. While my code works if I'm looking for a specific value, I'm unable to perform a search when a particular date is passed in. Essentially i'd like to view all of the children elements that occurred previous to that particular date.
My Investments models is this:
class Investment < ApplicationRecord
has_many :transactions
def count
final_quanity = 0
self.transactions.each do |transaction|
final_quanity+= transaction.quantity
end
final_quanity
end
def average_price
total_spent = 0
self.transactions.each do |transaction|
total_spent += transaction.price
end
total_spent
end
end
My transactions model is this:
class Transaction < ApplicationRecord
belongs_to :investment
end
Investment controller
class InvestmentsController < ApplicationController
def index
if params[:date]
# #investments = Investment.includes(:transactions).where(transactions: {quantity:10})
#investments = Investment.includes(:transactions).where("date > ?", params[:date])
else
#investments = Investment.all
end
render json: #investments
end
end
I'd like to only return the specific transactions that occurred before the date entered, by I'm having difficulty returning with a conditional. As you can see from the blocked out code, I'm able to successfully return entries that have a specific value. What's the appropriate way to complete the active record query with a conditional?
What's strange is that the following works:
#transactions = Transaction.where("date < ?", date)
While this doesn't:
#investments = Investment.includes(:transactions).where("date > ?", date)
Instead I get an error message that these's no such column as "date".
Essentially what's the best way to perform this action:
#investments = Investment.includes(:transactions).where( :transactions => {:price => 100})
except determining if a value is greater than or less than instead of just matching.

ActiveRecord ignores table_name_prefix

I've got situation where I need to define table_name and table_name_prefix within a model and for some reason table_name overrides table_name_prefix.
class ScheduleItem < ActiveRecord::Base
self.table_name = "schedule_item"
self.table_name_prefix = 'ACQ_IBM_T.'
end
The prefix is completely ignored in the queries. But, when I comment out the table_name part then the prefix is added. Anyone has seen strange behavior like this before?
In ActiveRecord::ModelSchema::ClassMethods, the table_name setter puts the value in #table_name:
def table_name=(value)
...
#table_name = value
And the table_name getter just uses the #table_name value if it is defined:
def table_name
reset_table_name unless defined?(#table_name)
#table_name
end
The table_name_prefix is only used to help Rails when it is trying to guess the table name based on the class name (in reset_table_name).
If you have a table name that Rails can't guess, you can do this:
class ScheduleItem < ActiveRecord::Base
self.table_name = "ACQ_IBM_T.schedule_item"
Or if you need to use the prefix somewhere else, you can do this:
class ScheduleItem < ActiveRecord::Base
self.table_name_prefix = 'ACQ_IBM_T.'
self.table_name = "#{table_name_prefix}schedule_item"

rails3 custom validation overlapping dates error

Building a validator that has to check multiple siblings who belong to the same (option) parent.
class Optionrate < ActiveRecord::Base
belongs_to :option
attr_accessible :from, :to, :option_id
validates_presence_of :from, :to
validate :not_overlap
scope :overlaps, ->(from, to) do
where "((from <= ?) and (to >= ?))", to, from
end
def overlaps?
overlaps.exists?
end
def overlaps
siblings.overlaps from, to
end
def not_overlap
errors.add(:key, t('overlap_message')) if overlaps?
end
def siblings
Optionrate.where('option_id = ?', option_id).all
end
is generating an error: "undefined method `overlaps' for []:Array" referring to statement
siblings.overlaps from, to
The fact that siblings is plural makes me assume it is expecting an array, so that's an oddity.
[Another was that the where statement was not accepting *where('option_id = ?', params[:option_id])* whence the record has yet to be created as the validation has not completed]
Please try to run the code after removing .all from Optionrate.where('option_id = ?', option_id).all because when you are using .Where then there is no need to use .all method.
Or
Take a look on following url for reference
http://guides.rubyonrails.org/3_2_release_notes.html#active-record

How to retrieve related records in Ruby on Rails?

I am trying to find a user's overdue invoices:
class User < ActiveRecord::Base
def overdue_invoices
invoices.where("overdue = ?", true)
end
end
class Invoice < ActiveRecord::Base
def overdue
balance > 0 && Date.today > due_date
end
end
The problem seems to be that overdue is a method on the Invoice model, not a database column.
How can I retrieve those records anyway? And does that even make sense or would it be better to store those true and false values in the database?
You should create an equivalent class method or scope for overdue on Invoice:
class Invoice < ActiveRecord::Base
def self.overdue
where('balance > 0').where('? > due_date', Date.today)
end
end
Then you can call overdue on an Invoice relation:
class User < ActiveRecord::Base
def overdue_invoices
invoices.overdue
end
end
Note that I’m assuming due_date is a database column, if it’s not, you cannot use this method—however, you may be able to replace it with SQL to calculate the due date from data that is in columns.

Using ActiveRecord's scope instruction to return a single result

I have the following class that works fine in my unit tests but I feel it could be simpler.
class License < ActiveRecord::Base
scope :active, lambda {
where("active_from <= ?", Date.today).order("version_number DESC")
}
end
def current_license
return License.active.first
end
public :current_license
I have tried appending the .first into the lambda clause but that causes an error.
How do I tell the scope I only want the first result, and thus eliminate the method current_license completely?
Make it a method, and you can get this:
class License < ActiveRecord::Base
def self.current_license
return License.where("active_from <= ?", Date.today).order("version_number DESC").first
end
end
As for the number of results, try to add a .limit(1). For more info, have a look here.

Resources