I'm trying to order the output of a where ActiveRecord query :
result = Class.where('a = ? AND b = ?', params[:a], params[:b])
I tried chaining order both before and after without succeeding, what am I missing ?
#Not working, the order is not modified compared to previous line
result = Class.where('a = ? AND b = ?', params[:a], params[:b]).order('c DESC')
Try to unscope the model, something like
result = Class.unscoped.where('a = ? AND b = ?', params[:a], params[:b]).order('c DESC')
Or delete the default scope if it is not used elsewhere
Related
Basically I'd like to return all people whose current job title is X and whose previous job title is Y. As an example, I have a talent whose current emnployment is "Airbnb (company_id = 1)" and whose previous employment is at "Youtube (company_id = 2)".
If I run a query to find talent where current employment is Airbnb:
Talent.joins(:job_histories).where(["job_histories.company_id = ? and job_histories.end_year = ?", 1, "Present"])
I get the person.
If I run a query where previous employment is Youtube (hence the end_year != "Present" below)
Talent.joins(:job_histories).where(["job_histories.company_id = ? and job_histories.end_year != ?", 2, "Present"])
I also get the same person.
However, if I chain them together to find talents where current employer is Airbnb AND previous employer is Youtube, like this:
#talents = Talent.all
#talents = #talents.joins(:job_histories).where(["job_histories.company_id = ? and job_histories.end_year = ?", 1, "Present"])
#talents = #talents.joins(:job_histories).where(["job_histories.company_id = ? and job_histories.end_year != ?", 2, "Present"])
I do not get any results. I've tried several variations of the query but none return anything.
The only way I can get it to work is by using the first query and then looping over each talent to find where job_histories.company_id == 2.
if params[:advanced_current_company] && params[:advanced_previous_company]
#talents = #talents.joins(:job_histories).where(job_histories: { company_id: params[:advanced_current_company] }).distinct if params[:advanced_current_company]
#talents.each do |talent|
talent.job_histories.each do |job_history|
if job_history.company_id == params[:advanced_previous_company][0].to_i
new_talents.append(talent.id)
end
end
end
#talents = Talent.where(id: new_talents)
end
Any direction would be amazing. Thanks!
You had the right idea with a double join of the job_histories, but you need to alias the job_histories table names to be able to differentiate between them in the query, as otherwise activerecord will think it's only one join that needs to be done.
Talent.joins("INNER JOIN job_histories as jh1 ON jh1.talent_id = talents.id")
.joins("INNER JOIN job_histories as jh2 ON jh2.talent_id = talents.id")
.where("jh1.company_id = ? and jh1.end_year = ?", 1, "Present")
.where("jh2.company_id = ? and jh2.end_year != ?", 2, "Present")
I'm trying to .sum a field from the following query:
def self.busqueda_general(params)
query = select('venta.Id,venta.TOTAL')
.distinct
.joins('left outer join detallevet ON venta.Documento=detallevet.Docto and venta.RutaId=detallevet.RutaId')
.where("(venta.RutaId = :rutaId or :rutaId = '') AND (detallevet.Articulo = :articulo or :articulo = '') AND (venta.CodCliente = :codcliente or :codcliente = '') AND (venta.IdEmpresa = :idempresa)",{rutaId: params[:search], articulo: params[:search3], codcliente: params[:search2], idempresa: params[:search6]})
query = query.where('venta.Fecha >= ? AND venta.Fecha <= ?', (params[:search4].to_date.beginning_of_day).strftime('%Y-%m-%d %T'), (params[:search5].to_date.end_of_day).strftime('%Y-%m-%d %T')) if params[:search4].present? and params[:search5].present?
query
end
In the method of the controller I call the query and sum it as follows:
#monto_total = Vent.busqueda_general(params).sum(:TOTAL)
but the problem is that the query is showing me records that are not repeated thanks to .distinct but with the .sum is adding up all the records including the repeated ones, ignoring the .distinct
Try this
#monto_total = Vent.busqueda_general(params).sum(:TOTAL).to_f
you can to use to_s (to convert in string) to_f -> float, to_i -> integer
You have a group by clause, so you get one sum(Total) for every combination of ID/Total.
.group('venta.Id,venta.TOTAL')
To me looks like you don't need this group by clause.
UPDATE::
query = where(Id: select('venta.Id')
.joins('left outer join detallevet ON venta.Documento=detallevet.Docto and venta.RutaId=detallevet.RutaId')
.where("(venta.RutaId = :rutaId or :rutaId = '') AND (detallevet.Articulo = :articulo or :articulo = '') AND (venta.CodCliente = :codcliente or :codcliente = '') AND (venta.IdEmpresa = :idempresa)",{rutaId: params[:search], articulo: params[:search3], codcliente: params[:search2], idempresa: params[:search6]}))
Change your main query to this keeping everything else same. Ideal way would be to move join on detallevet to where clause.
Assume I have an arbitrary number of Group records and I wanna query User record which has_many :groups, the catch is that users are queries by two bound fields from the groups table.
At the SQL level, I should end up with something like this:
SELECT * FROM users where (categories.id = 1 OR users.status = 0) OR(categories.id = 2 OR users.status = 1) ... -- to infinity
This is an example of what I came up with:
# Doesn't look like a good solution. Just for illustration.
or_query = groups.map do |g|
"(categories.id = #{g.category.id} AND users.status = #{g.user_status.id} )"
end.join('OR')
User.joins(:categories).where(or_query) # Works
What I think I should be doing is something along the lines of this:
# Better?
or_query = groups.map do |g|
"(categories.id = ? AND users.status = ? )".bind(g.category.id, g.user_status.id) #Fake method BTW
end.join('OR')
User.joins(:categories).where(or_query) # Works
How can I achieve this?
There has to be a better way, right?
I'm using Rails 4.2. So the shiny #or operator isn't supported for me.
I would collect the condition parameters separately into an array and pass that array (splatted, i.e. as an arguments list) to the where condition:
or_query_params = []
or_query = groups.map do |g|
or_query_params += [g.category_id, g.user_status.id]
"(categories.id = ? AND users.status = ?)"
end.join(' OR ')
User.joins(:categories).where(or_query, *or_query_params)
Alternatively, you might use ActiveRecord sanitization:
or_query = groups.map do |g|
"(categories.id = #{ActiveRecord::Base.sanitize(g.category_id)} AND users.status = #{ActiveRecord::Base.sanitize(g.user_status.id)})"
end.join(' OR ')
User.joins(:categories).where(or_query)
I was wondering if there's a better way to do this:
def conditions(obj)
if self.setor.present?
obj = obj.joins(:negocios_setores).where("setor_id = ?", self.setor.id)
end
if self.uf.present?
obj = obj.joins(localizacao: [:uf]).where("uf_id = ?", self.uf_id)
end
if self.municipio.present?
obj = obj.joins(localizacao: [:municipio]).where("municipio_id = ?", self.municipio_id)
end
if !self.lucro_liquido_min.to_f.zero?
obj = obj.where("lucro_liquido_anual BETWEEN ? and ?", self.lucro_liquido_min, self.lucro_liquido_max)
end
if !self.faturamento_min.to_f.zero?
obj = obj.where("faturamento_bruto_anual BETWEEN ? and ?", self.faturamento_min, self.faturamento_max)
end
if !self.valor_min.to_f.zero?
obj = obj.where("valor BETWEEN ? and ?", self.valor_min, self.valor_max)
end
obj
end
Does rails 4 provide something to only do the condition if the value is present instead of placing it with a NULL value?
I don't believe that there is any way to do exactly what you mentioned. I've run into the same type of concatenation of queries.
To clean up a bit and make this tighter, you can use one-line if and unless. I think this is a bit cleaner and still readable.
def conditions(obj)
obj = obj.joins(:negocios_setores).where(setor: setor) if setor.present?
obj = obj.joins(localizacao: [:uf]).where("uf_id = ?", uf_id) if uf.present?
obj = obj.joins(localizacao: [:municipio]).where("municipio_id = ?", municipio_id) if municipio.present?
obj = obj.where("lucro_liquido_anual BETWEEN ? and ?", lucro_liquido_min, lucro_liquido_max) unless lucro_liquido_min.to_f.zero?
obj = obj.where("faturamento_bruto_anual BETWEEN ? and ?", faturamento_min, faturamento_max) unless faturamento_min.to_f.zero?
obj = obj.where("valor BETWEEN ? and ?", valor_min, valor_max) unless valor_min.to_f.zero?
obj
end
I also changed the first query to use Rails style queries rather than SQL in the where.
I'm doing a search on a model using a scope. This is being accessed by a search form with the search parameter q. Currently I have the code below which works fine for searches on tags associated with the model. But I would also like to search the title field. If I add to this scope then I will get all results where there is a tag and title matching the search term.
However, I need to return results that match the company_id and category_id, and either/or matching title or tag. I'm stuck with how to add an OR clause to this scope.
def self.get_all_products(company, category = nil, subcategory = nil, q = nil)
scope = scoped{}
scope = scope.where "company_id = ?", company
scope = scope.where "category_id = ?", category unless category.blank?
scope = scope.tagged_with(q) unless q.blank?
scope
end
I'm using Rails 3.
Ever consider Arel? You can do something like this
t = TableName.arel_table
scope = scope.where(t[:title].eq("BLAH BLAH").or(t[:tag].eq("blah blah")))
or else you can do
scope = scope.where("title = ? OR tag = ", title_value, tag_value)
I could be wrong, but I don't think scopes can help you to construct an or condition. You'll have to hand-write the code to buid your where clause instead. Maybe something like this...
clause = "company_id=?"
qparams = [company]
unless category.blank?
clause += " or category_id=?"
qparams <= category
end
scope.where clause, *qparams