Error when combining search scopes - ruby-on-rails

I have a web-service that allows clients to search for articles with query parameters.It works fine if only one parameter is included but fails if I combine search_query and category. This is based on Comfortable_Mexican_Sofa where for_category is found. Even if I remove the order statement i get this error.
error
PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY
expressions must appear in select list LINE 1:
...ms_categories"."label" = 'Company News' ORDER BY pg_search_...
^ : SELECT DISTINCT "comfy_cms_pages".* FROM "comfy_cms_pages" INNER JOIN
"comfy_cms_categorizations" ON
"comfy_cms_categorizations"."categorized_id" = "comfy_cms_pages"."id"
AND "comfy_cms_categorizations"."categorized_type" = $1 INNER JOIN
"comfy_cms_categories" ON "comfy_cms_categories"."id" =
"comfy_cms_categorizations"."category_id" INNER JOIN (SELECT
"comfy_cms_pages"."id" AS pg_search_id,
(ts_rank((to_tsvector('simple',
coalesce("comfy_cms_pages"."content_cache"::text, '')) ||
to_tsvector('simple', coalesce("comfy_cms_pages"."label"::text, ''))),
(to_tsquery('simple', ''' ' || 'austin' || ' ''' || ':')), 0)) AS
rank FROM "comfy_cms_pages" WHERE (((to_tsvector('simple',
coalesce("comfy_cms_pages"."content_cache"::text, '')) ||
to_tsvector('simple', coalesce("comfy_cms_pages"."label"::text, '')))
## (to_tsquery('simple', ''' ' || 'austin' || ' ''' || ':')))))
pg_search_comfy_cms_pages ON "comfy_cms_pages"."id" =
pg_search_comfy_cms_pages.pg_search_id WHERE (layout_id = '1' AND
is_published = 't') AND "comfy_cms_categories"."label" = 'Company
News' ORDER BY pg_search_comfy_cms_pages.rank DESC,
"comfy_cms_pages"."id" ASC, "comfy_cms_pages"."created_at" DESC
app/models/article.rb
class Article < Comfy::Cms::Page
cms_is_categorized
include PgSearch
pg_search_scope :search_by_keywords, against: [:content_cache, :label], using: { tsearch: { any_word: true, prefix: true } }
app/commands/search_articles_command.rb
class SearchArticlesCommand
def initialize(params = {})
#since = params[:since_date]
#keys = params[:search_query]
#category = params[:category]
end
def execute
Article.unscoped do
query = if #since.present?
Article.article.since_date(#since)
else
Article.published_article
end
query = query.for_category(#category) if #category.present?
query = query.search_by_keywords(#keys) if #keys.present?
query.where('').order(created_at: :desc)
end
end
end
comfortable-mexican-sofa/lib/comfortable_mexican_sofa/extensions/is_categorized.rb
module ComfortableMexicanSofa::IsCategorized
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def cms_is_categorized
include ComfortableMexicanSofa::IsCategorized::InstanceMethods
has_many :categorizations,
:as => :categorized,
:class_name => 'Comfy::Cms::Categorization',
:dependent => :destroy
has_many :categories,
:through => :categorizations,
:class_name => 'Comfy::Cms::Category'
attr_accessor :category_ids
after_save :sync_categories
scope :for_category, lambda { |*categories|
if (categories = [categories].flatten.compact).present?
self.distinct.
joins(:categorizations => :category).
where('comfy_cms_categories.label' => categories)
end
}
end
end
module InstanceMethods
def sync_categories
(self.category_ids || {}).each do |category_id, flag|
case flag.to_i
when 1
if category = Comfy::Cms::Category.find_by_id(category_id)
category.categorizations.create(:categorized => self)
end
when 0
self.categorizations.where(:category_id => category_id).destroy_all
end
end
end
end
end
ActiveRecord::Base.send :include, ComfortableMexicanSofa::IsCategorized
Updated Error
PG::SyntaxError: ERROR: syntax error at or near "."
LINE 4: ...e = 'Class' AND categorized_id = 'comfy_cms_pages'.'id' AND ...
^
: SELECT "comfy_cms_pages".* FROM "comfy_cms_pages" INNER JOIN (SELECT "comfy_cms_pages"."id" AS pg_search_id, (ts_rank((to_tsvector('simple', coalesce("comfy_cms_pages"."content_cache"::text, '')) || to_tsvector('simple', coalesce("comfy_cms_pages"."label"::text, ''))), (to_tsquery('simple', ''' ' || 'austin' || ' ''' || ':*')), 0)) AS rank FROM "comfy_cms_pages" WHERE (((to_tsvector('simple', coalesce("comfy_cms_pages"."content_cache"::text, '')) || to_tsvector('simple', coalesce("comfy_cms_pages"."label"::text, ''))) ## (to_tsquery('simple', ''' ' || 'austin' || ' ''' || ':*'))))) pg_search_comfy_cms_pages ON "comfy_cms_pages"."id" = pg_search_comfy_cms_pages.pg_search_id WHERE "comfy_cms_pages"."layout_id" = $1 AND "comfy_cms_pages"."is_published" = $2 AND (
EXISTS (
SELECT 1 FROM categorizations
WHERE categorized_type = 'Class' AND categorized_id = 'comfy_cms_pages'.'id' AND category_id IN (2)
)) ORDER BY pg_search_comfy_cms_pages.rank DESC, "comfy_cms_pages"."id" ASC
working solution but not a scope and have to be careful of order its being called
def self.for_category(_category)
Comfy::Cms::Categorization.includes(:category).references(:category).select(:categorized).pluck(:categorized_id)
find(ids)
end

I think it's best to override for_category built-in filter of your CMS. Too many joins in that query.
Override for_category like this:
scope :for_category, lambda { |*categories|
if (categories = [categories].flatten.compact).present?
self_ids = "{connection.quote_table_name(self.table_name)}.#{connection.quote_column_name(self.primary_key)}"
self.where(
"EXISTS (" +
Comfy::Cms::Categorization.select('1').
where(categorized_type: self.name).
where('categorized_id' => self_ids).
where(category_id: Comfy::Cms::Category.where(label: categories).pluck(:id)).to_sql +
")"
)
end
}
More on SQL EXISTS usage in Rails you can read in my Rails: SQL EXISTS brief how-to.
More on why you bump into that error you can read in question and answer here.
Specifically, pg_search wants order your results by rank. And for_category wants to select distinct fields of Article only, and doesn't care about search rank. Changing its code to use simple EXISTS instead of complex JOIN query will fix that.

I was able to solve this problem by applying reorder to the result of the pg_search result.
search_command.rb
class SearchArticlesCommand
def initialize(params = {})
#since = params['since_date']
#keys = params['search_query']
#category = params['category']
end
def execute
Article.unscoped do
query = Article.article
query = if #since.present?
query.since_date(#since)
else
query.published
end
query = query.for_category(#category) if #category.present?
query = query.search_by_keywords(#keys).reorder('updated_at DESC') if #keys.present?
query
end
end
end
I also overrode for_category (not required)
article.rb
scope :for_category, (lambda do |category|
published
.joins(:categories)
.group(:id)
.where('comfy_cms_categories.label' => category)
.select('comfy_cms_pages.*')
end)

Related

Aliasing the source table

Is there a way to alias the source table in the context of a single scope ?
I tried this :
scope = User.all
scope.arel.source.left.table_alias = "toto"
scope.where(firstname: nil) => "SELECT `toto`.* FROM `users` `toto` WHERE `toto`.`firstname` IS NULL"
The problem is that the model class keeps the alias for all subsequent queries :
User.all => "SELECT `toto`.* FROM `users` `toto`"
Edit
I added this method to ApplicationRecord
def self.alias_source(table_alias)
klass = Class.new(self)
klass.all.source.left.table_alias = table_alias
klass
end
Now, I can do :
User.alias_source(:toto).where(firstname: nil) => "SELECT `toto`.* FROM `users` `toto` WHERE `toto`.`firstname` IS NULL"
I added this method to ApplicationRecord
def self.alias_source(table_alias)
klass = Class.new(self)
klass.all.source.left.table_alias = table_alias
klass
end
Now, I can do :
User.alias_source(:toto).where(firstname: nil) => "SELECT `toto`.* FROM `users` `toto` WHERE `toto`.`firstname` IS NULL"
Since creating Anonymous Classes that inherit from ActiveRecord::Base will cause memory bloat, I am not sure I would recommend it (See Here: https://github.com/rails/rails/issues/31395).
Maybe a better implementation would be to execute in a block form instead e.g. yield the aliased table to the block then set it back afterwards?
e.g.
def self.with_table_alias(table_alias, &block)
begin
self.all.source.left.table_alias = table_alias
block.call(self)
ensure
self.all.source.left.table_alias = nil
end
end
Usage
User.with_table_alias(:toto) do |scope|
puts scope.joins(:posts).where(firstname: "Ruur").to_sql
end
# "SELECT `toto`.*
# FROM
# `users` `toto`
# INNER JOIN `posts` ON `posts`.`user_id` = `toto`.`id`
# WHERE
# `toto`.`firstname` = 'Ruur'"
puts User.all.to_sql
# "SELECT `users`.* FROM `users`
WARNING: THIS HAS NOT BE TESTED BEYOND WHAT IS SHOWN HERE AND I WOULD NOT RECOMMEND THIS IN A PRODUCTION ENVIRONMENT WITHOUT EXTENSIVE TESTING FOR EDGE CASES AND OTHER GOTCHAS
Update To address desired implementation
module ARTableAlias
def alias_table_name=(val)
#alias_table_name = val
end
def alias_table_name
#alias_table_name ||= "#{self.table_name}_alias"
end
def alias_source
#alias_klass ||= Class.new(self).tap do |k|
k.all.source.left.table_alias = alias_table_name
end
end
end
Then usage as:
class User < ApplicationRecord
extend ARTableAlias
alias_table_name = :toto
end
User.alias_source.where(first_name = 'Ruur')
#=> SELECT `toto`.* FROM `users` `toto` WHERE `toto`.`first_name` = 'Ruur'
User.where(first_name = 'Ruur')
#=> SELECT `users`.* FROM `users` WHERE `users`.`first_name` = 'Ruur'
User.alias_source === User.alias_source
#=> true

Need help refactoring to use .where clause - ruby on rails

I have the following code which is legacy code and I need to refactor it to .where clauses but I'm having issues in refactoring it and the best way to do it.
Here is the code
# legacy
#debit_transactions = FinancialTransaction.legacy_find(
:all,
:include => [:project, :department, :stock, :debit_account, :credit_account, :transaction_type],
:conditions => ["dr_account_id = ?", #customer.id],
:order => 'financial_transactions.id desc',
:limit => 20)
# refactor attempt
#debit_transactions = FinancialTransaction.where(dr_account_id: #dr_account_id, customer: #customer.id).order('financial_transactions.id desc').limit(20)
# legacy
contact_or = ''
contact_or = ' OR contact_id IN(?) ' if #customer.contacts.present?
#customer_complaints = Event.legacy_find(:all, { :order => 'id desc', :limit => 10, :conditions => ["complaint is true and (customer_account_id = ? #{contact_or} )", #customer.id].push_if(#customer.contacts.to_a.map(&:id), #customer.contacts.present?) })
# refactor attempt
#customer_complaints = Event.where(complaints: true, customer_account_id: [#customer_account_id], customer: #customer.id).order('id desc').limit(10)
Any help would be appreciated
edit some methods that might be help in understanding the legacy_find
def self.legacy_find(type, args=nil)
# need to add capability to handle array of id's
if type.kind_in?([Numeric, String, Array]) && !args
result = self.find(type)
elsif !args
result = self.send(type.to_s)
else
result = self
if type.kind_of?(Array)
if !args[:conditions]
args[:conditions] = ["1 = 1"]
elsif args[:conditions].kind_of?(String)
args[:conditions] = [args[:conditions]]
end
args[:conditions][0] = '(' + args[:conditions][0] + ')'
args[:conditions][0] += " AND `" + self.table_name + "`.`id` in(" + type.join(',') + ")"
elsif type && !type.kind_of?(Symbol)
if !args[:conditions]
args[:conditions] = ["1 = 1"]
elsif args[:conditions].kind_of?(String)
args[:conditions] = [args[:conditions]]
end
args[:conditions][0] = '(' + args[:conditions][0] + ')'
args[:conditions][0] += " AND `" + self.table_name + "`.`id` = ?"
args[:conditions].push(type)
end
result = self.legacy_conditions(args)
if type && ((type.kind_of?(String) && type.to_i.to_s == type) || type.kind_of?(Numeric))
result = result.first
elsif type && !type.kind_of?(Symbol)
result = result.to_a
else
result = type ? result.send((type == :all ? 'to_a' : type).to_s) : result
end
end
new_result = result
return new_result
end
def self.legacy_count(args=nil)
new_result = self.legacy_conditions(args).count
end
def self.legacy_sum(col, args=nil)
new_result = self.legacy_conditions(args).sum(col.to_s)
end
def self.legacy_conditions(args)
return self if !args
args[:conditions] = [] if args[:conditions] && args[:conditions][0].kind_of?(String) && args[:conditions][0].size == 0
result = self
result = result.where(args[:conditions]) if (args.has_key?(:conditions) && args[:conditions] && args[:conditions].size > 0)
result = result.select(args[:select]) if args.has_key?(:select) && args[:select]
result = result.includes(args[:include]) if args.has_key?(:include) && args[:include]
result = result.includes(args[:include_without_references]) if args.has_key?(:include_without_references) && args[:include_without_references]
result = result.references(args[:include]) if args.has_key?(:include) && args[:include]
result = result.joins(args[:joins]) if args.has_key?(:joins) && args[:joins]
result = result.order(args[:order]) if args.has_key?(:order) && args[:order]
result = result.group(args[:group]) if args.has_key?(:group) && args[:group]
result = result.limit(args[:limit]) if args.has_key?(:limit) && args[:limit]
result = result.offset(args[:offset]) if args.has_key?(:offset) && args[:offset]
result = result.from(args[:from]) if args.has_key?(:from) && args[:from]
result = result.lock(args[:lock]) if args.has_key?(:lock) && args[:lock]
result = result.readonly(args[:readonly]) if args.has_key?(:readonly) && args[:readonly]
result
end
Honestly why this code exists is beyond me so I'm trying to phase it out.
edit 2
Based on the answers below I've come up with the following
#debit_transactions = FinancialTransaction
.includes(:project, :department, :stock, :debit_account, :credit_account, :transaction_type)
.where(dr_account_id: #dr_account_id)
.order(id: :desc)
.limit(20)
#credit_transactions = FinancialTransaction
.includes(:project, :department, :stock, :debit_account, :credit_account, :transaction_type)
.where(cr_account_id: #cr_account_id)
.order(id: :desc)
.limit(20)
contact_or = ''
contact_or = ' OR contact_id IN(?) ' if #customer.contacts.size > 0
#customer_complaints = Event.where(customer_account_id: #customer_id, complaint: true).order(id: :desc).limit(10).or(Event.where(contact_id: #customer.contacts)) if #customer.contacts.present?
#customer_leads = Event.where(customer_account_id: #customer_id, lead: true).order(id: :desc).limit(10)
#customer_quotes = SalesQuote.where(customer_account_id: #customer_id).or(SalesQuote.where(contact_id: #contact_id)).order(id: :desc).limit(10)
#customer_orders = SalesOrder.where(customer_account_id: #customer_id).order(id: :desc).limit(10)
#customer_invoices = Invoice.where(customer_account_id: #customer_id).order(id: :desc).limit(10)
#customer_credits = CreditNote.where(customer_account_id: #customer_id).order(id: :desc).limit(10)
#customer_opportunities = Opportunity.where(customer_account_id: #customer_id).or(Opportunity.where(contact_id: #contact_id)).order(id: :desc).limit(10)
#customer_estimates = Estimate.where(customer_account_id: #customer_id).or(Estimate.where(contact_id: #contact_id)).order(id: :desc).limit(10)
#customer_support_tickets = SupportTicket.where(customer_account_id: #customer_id).order(id: :desc).limit(10)
#financial_matching_sets = FinancialMatchingSet.where(customer_account_id: #customer_id).order(id: :desc).limit(10)
However, I'm getting the following
Mysql2::Error: Unknown column 'sales_orders.customer_account_id' in 'where clause': SELECT `sales_orders`.* FROM `sales_orders` WHERE `sales_orders`.`customer_account_id` IS NULL ORDER BY `sales_orders`.`id` DESC LIMIT 10
the best way to do it.
I don't have a concrete answer to this, but there's a few things you could try, such as:
Write test cases for the behaviour of the old implementation, thus ensuring that they still behave the same with the new implementation. (Maybe you already have some such tests in place??!!)
Write test cases for the implementation of the old vs new code, by checking query.to_sql remains unchanged?!
Try running both versions on production, in parallel, assuming you have good error logging. For example, could you gradually switch over 10% of users to use the "new" implementations, thus catching any errors without causing mass failures for everyone?
But anyway... Aside from the pain of actually rewriting all of these in a safe/robust/well-tested way:
First query:
#debit_transactions = FinancialTransaction.legacy_find(
:all,
:include => [:project, :department, :stock, :debit_account, :credit_account, :transaction_type],
:conditions => ["dr_account_id = ?", #customer.id],
:order => 'financial_transactions.id desc',
:limit => 20)
# refactor attempt
#debit_transactions = FinancialTransaction
.where(dr_account_id: #dr_account_id, customer: #customer.id)
.order('financial_transactions.id desc')
.limit(20)
This refactor ignores the include parameters. The legacy method says:
# ...
result = result.includes(args[:include]) if args.has_key?(:include) && args[:include]
result = result.references(args[:include]) if args.has_key?(:include) && args[:include]
# ...
So, your version should have been:
#debit_transactions = FinancialTransaction
.includes([:project, :department, :stock, :debit_account, :credit_account, :transaction_type])
.references([:project, :department, :stock, :debit_account, :credit_account, :transaction_type])
.where(dr_account_id: #dr_account_id, customer: #customer.id)
.order('financial_transactions.id desc')
.limit(20)
Second query:
# legacy
contact_or = ''
contact_or = ' OR contact_id IN(?) ' if #customer.contacts.present?
#customer_complaints = Event.legacy_find(
:all,
:order => 'id desc',
:limit => 10,
:conditions => ["complaint is true and (customer_account_id = ? #{contact_or} )", #customer.id].push_if(#customer.contacts.to_a.map(&:id), #customer.contacts.present?)
)
# refactor attempt
#customer_complaints = Event
.where(complaints: true, customer_account_id: [#customer_account_id], customer: #customer.id)
.order('id desc')
.limit(10)
Your refactor ignores the OR clause in the condition; you've written this as 3 AND clauses instead.
I think this can be written as something like:
Event.where(customer_account_id: [#customer_account_id])
.or(Event.where(customer: #customer.id))
.merge(Event.where(complaints: true))
.order('id desc')
.limit(10)
...Or something like that. Check the generated SQL in both cases.
The first query is relatively straight forward:
#debit_transactions = FinancialTransaction
# you missed the includes
.includes(
:project, :department, :stock, :debit_account,
:credit_account, :transaction_type
)
.where(
dr_account_id: #dr_account_id.id,
)
.order(id: :desc)
.limit(20)
Then second query is a bit tougher.
You can create a WHERE x IN (...) clause simply by passing an array:
#debit_transactions = FinancialTransaction.where(
id: [1,2,3]
)
You can also create a WHERE x IN (subquery) by passing a ActiveRecord::Relation:
Event.where(contact_id: #customer.contacts)
This is far more effective them using .map(:id) or .ids as you remove a full round trip to the DB.
Support for OR was added in Rails 5:
scope = Event.where(customer_account_id: #customer_id)
scope = scope.or(Event.where(contact_id: #customer.contacts)) if #customer.contacts.present?
So altogether it would look something like:
scope = Event.where(
customer_account_id: #customer_id
complaint: true
).order('id desc')
.limit(10)
scope = scope.or(Event.where(contact_id: #customer.contacts)) if #customer.contacts.present?

Rails active record where chaining losing scope

Model Food has scope expired:
Food.rb
class Food < ApplicationRecord
default_scope { where.not(status: 'DELETED') }
scope :expired, -> { where('exp_date <= ?', DateTime.now) }
belongs_to :user
end
In my controller I'm chaining where conditions to filter foods by user and status:
query_type.rb
def my_listing_connection(filter)
user = context[:current_user]
scope = Food.where(user_id: user.id)
if filter[:status] == 'ARCHIVED'
# Line 149
scope = scope.where(
Food.expired.or(Food.where(status: 'COMPLETED'))
)
else
scope = scope.where(status: filter[:status])
end
scope.order(created_at: :desc, id: :desc)
# LINE 157
scope
end
Here is the rails log:
Food Load (2.7ms) SELECT `foods`.* FROM `foods` WHERE `foods`.`status` !=
'DELETED'
AND ((exp_date <= '2020-07-02 09:58:16.435609') OR `foods`.`status` = 'COMPLETED')
↳ app/graphql/types/query_type.rb:149
Food Load (1.6ms) SELECT `foods`.* FROM `foods` WHERE `foods`.`status` != 'DELETED'
AND `foods`.`user_id` = 1 ORDER BY `foods`.`created_at` DESC, `foods`.`id` DESC
↳ app/graphql/types/query_type.rb:157
Why does active records query loses expired scope (and a condition) in line 157?
It is ignored because where doesn't expect scopes like that. But you can use merge instead. Replace
scope = scope.where(
Food.expired.or(Food.where(status: 'COMPLETED'))
)
with
scope = scope.merge(Food.expired)
.or(Food.where(status: 'COMPLETED'))
or
scope = scope.where(status: 'COMPLETED').or(Food.expired)

Better way to build multiple conditions in Rails 2.3

I'm developing with Rails 2.3.8 and looking for a better way to build find conditions.
On search page, like user search, which user sets search conditions, find conditions are depends on the condition which user have chosen, e.g age, country, zip-code.
I've wrote code below to set multiple find conditions.
# Add condition if params post.
conditions_array = []
conditions_array << ['age > ?', params[:age_over]] if params[:age_over].present?
conditions_array << ['country = ?', params[:country]] if params[:country].present?
conditions_array << ['zip_code = ?', params[:zip_code]] if params[:zip_code].present?
# Build condition
i = 0
conditions = Array.new
columns = ''
conditions_array.each do |key, val|
key = " AND #{key}" if i > 0
columns += key
item_master_conditions[i] = val
i += 1
end
conditions.unshift(columns)
# condiitons => ['age > ? AND country = ? AND zip_code = ?', params[:age], params[country], prams[:zip_code]]
#users = User.find(:all,
:conditions => conditions
)
This code works fine but it is ugly and not smart.
Is there better way to build find conditions?
Named scopes could make it a bit more readable, albeit bulkier, while still preventing SQL injection.
named_scope :age_over, lambda { |age|
if !age.blank?
{ :conditions => ['age > ?', age] }
else
{}
end
}
named_scope :country, lambda { |country|
if !country.blank?
{ :conditions => ['country = ?', age] }
else
{}
end
}
named_scope :zip_code, lambda { |zip_code|
if !zip_code.blank?
{ :conditions => ['zip_code = ?', age] }
else
{}
end
}
And then when you do your search, you can simply chain them together:
#user = User.age_over(params[:age_over]).country(params[:country]).zip_code(params[:zip_code])
I have accidentally run on your questions, and even it is old one, here is the answer:
After defining your conditions, you could use it like this:
# Add condition if params post.
conditions_array = []
conditions_array << ["age > #{params[:age_over]}"] if params[:age_over].present?
conditions_array << ["country = #{params[:country]}"] if params[:country].present?
conditions_array << ["zip_code = #{params[:zip_code]}"] if params[:zip_code].present?
conditions = conditions_array.join(" AND ")
#users = User.find(:all, :conditions => conditions) #Rails 2.3.8
#users = User.where(conditions) #Rails 3+

Refactor: Multiple params in find query

Need some help refactoring this if/else block that builds the conditions for a find query.
if params[:status] && params[:carrier]
conditions = ["actual_delivery IS NOT NULL AND actual_delivery > scheduled_delivery AND status_id = ? AND carrier_id = ?", status.id, carrier.id]
elsif params[:status]
conditions = ["actual_delivery IS NOT NULL AND actual_delivery > scheduled_delivery AND status_id = ?", status.id]
elsif params[:carrier]
conditions = ["actual_delivery IS NOT NULL AND actual_delivery > scheduled_delivery AND carrier_id = ?", carrier.id]
else
conditions = ["actual_delivery IS NOT NULL AND actual_delivery > scheduled_delivery"]
end
#packages = Package.find(:all, :conditions => conditions)
I recommend creating a scope in your model, to take care of the first part of your query that is always the same in this action:
class Package < ActiveRecord::Base
named_scope :late_deliveries, :conditions => "actual_delivery IS NOT NULL AND actual_delivery > scheduled_delivery"
end
Now you can refactor your action like this:
def index
conditions = {}
[:status, :carrer].each{|param| conditions[param] = params[param] if params[param]}
#packages = Package.late_deliveries.find(:conditions => conditions)
end
If :carrier and :status are the only two parameters to this action, then it's even simpler:
def index
#packages = Package.late_deliveries.find(:conditions => params)
end
I hope this helps!
You could do:
conditions = "actual_delivery IS NOT NULL AND actual_delivery > scheduled_delivery"
conditions += " AND status_id = #{status.id}" if params[:status]
conditions += " AND carrier_id = #{carrier.id}" if params[:carrier]
#packages = Package.all(:conditions => [conditions])

Resources