removing records from activerecord results - ruby-on-rails-4

product_keywords is an array of strings.
gifts is the result of an ActiveRecord query
Basically, I want to remove certain results from gifts (see if clause). If gifts was a normal array, it'd be fairly easy, but I don't want to lose the ActiveRecord functionality.
gifts.each do | gift |
if product_keywords.all? { |keyword| gift.product.name.downcase.include? keyword }
# ?????
end
end
ETA: I don't want to edit the database. I just want to remove certain records from the results object.

Try with
gifts.reject!{ |gift| !product_keywords.include?(gift.product.name.downcase) }

This seems to be what I was looking for.
gifts = gifts.reject { | gift | !product_keywords.all? { |keyword| gift.product.name.downcase.include? keyword } }

Related

ArangoDB query find name consisting of two or more parts

i am quite new to arangodb and AQL. What i am trying to do is to find names and surnames with query that have two or more parts that may or may not include spaces (" ") to divide those said parts.
As i went through documents, I figured that those fileds should be indexed as full-text indexes and query would be something like
FOR u IN FULLTEXT(collection, field, "search") RETURN u
Now my question is how to utilize the above query for a Persian/Arabic names such as
سید امیر حسین
Keep in mind that this name comes from an input of a user and it could be in the following formats such as
سید امیر حسین/سید امیرحسین/سیدامیر حسین/سیدامیرحسین
Note the various types of names with/without spaces. I tried the follwoing query F
FOR u IN FULLTEXT(collection, field, "سید,|امیر,|حسین,|سیدامیرحسین") RETURN u
But the problem is this will also result of fetching the name because i reckon the use of OR ( | ) operator.
سید محمد
which is not my intention. So what am i doing wrong or missing here ?
Many thanks in advance and excuse my noobiness
PS : arango 3.8.3

Why is this ATL helper wrong?

I'm new to ATL and OCL and I'm trying to transform this metamodel:
enter image description here
into this one:
enter image description here
The helper is meant to take all the tests created by the user admin and after that sum the id's of the Actions of that test.
I've done this helper:
helper def: actionsId: Integer = Test!Test.allInstances()->select(i | i.md.user='admin')->collect(n | n.act.id.toInteger())->sum();
But when I run the transformation I'm having this error:
org.eclipse.m2m.atl.engine.emfvm.VMException: Collections do not have properties, use ->collect()
This error is in the collect(n | n.act.id.toInteger()) part of the helper.
The rest of my code is this:
rule Testset2Testcase{
from s: Test!Test
to r: Testcase!Testcase(
ident <- thisModule.actionId.toString(),
date <- s.md.date,
act <- thisModule.resolveTemp(s.act,'a')
)
do{
'Bukatuta'.println();
}
}
rule Action2Activity{
from s: Test!Action
to a: Testcase!Activity(
ident <- s.id
)
}
Sorry for my bad english.
My teacher helped me with this.
The problem was in the helper. Doing this:
helper def: actionsId: Integer = Test!Test.allInstances()->select(i | i.md.user='admin')->collect(n | n.act.id.toInteger())->sum();
I was trying to take the id of a collection of collections of the type Action instead of taking the id of each objects.
With that helper I was taking a collection of collections so using flattener this collection of collections became a collection of Actions.
The helper written in a correct way looks like this:
helper def: actionsId: Integer = Test!Test.allInstances()->select(i | i.md.user='admin')->collect(n | n.act)->flatten()->collect(x | x.id.toInteger())->sum();
Your expression looks plausible, but without your metamodel it is difficult to see where ATL is unhappy about use of a Collection property. If Test::md is a collection, the expression would just be stupid, though not for the reason given.
If ATL's hovertext doesn't help you understand your types, you might enter the same expression into the OCL Xtext Console and carefully hover over "." and "md" to get its accurate type analysis.
But beware, ATL has an independently developed embedded OCL that is not as rich as Eclipse OCL. Perhaps your expression is too complex for ATL; try breaking it up with let's.

How to get the most accurate term in regex?

I have an angular app using the mongodb sdk for js.
I would like to suggest some words on a input field for the user from my words collection, so I did:
getSuggestions(term: string) {
var regex = new stitch.BSON.BSONRegExp('^' +term , 'i');
return from(this.words.find({ 'Noun': { $regex: regex } }).execute());
}
The problem is that if the user type for example Bie, the query returns a lot of documents but the most accurated are the last ones, for example Bier, first it returns the bigger words, like Bieberbach'sche Vermutung. How can I deal to return the closests documents first?
A regular-expression is probably not enough to do what you are intending to do here. They can only do what they're meant to do – match a string. They might be used to give you a candidate entry to present to the user, but can't judge or weigh them. You're going to have to devise that logic yourself.

Rails: efficient way of finding/replacing words in a large collection of records using a hash filter

Just wondering what the best way to approach this would be,
I have a large american to british english filter with about 2000 items
filter = {"authorized"=>"authorised"........}
and a large collection of about 4000 records
posts = Post.all
what would be the most efficient way to do a search and replace across a couple of properties (say post.title and post.description) for each record while maintaining original casing(ie. replace all characters after the first one only)?
edit: updated hash count
I would think about using gsub with a Regexp.union and the hash syntax:
string.gsub(Regexp.union(filter.keys), filter)
To iterate over all posts use find_each to improve memory usage:
FILTER = { "authorized" => "authorised", ... }
FILTER_REGEXP = Regexp.new(Regexp.union(FILTER.keys), Regexp::IGNORECASE)
def translate(string)
string.gsub(FILTER_REGEXP, FILTER)
end
Post.find_each do |post|
post.update(
title: translate(post.title),
description: translate(post.description)
)
end
To support the original casing, I would add both versions to the hash (upcase and lowercase), that makes the whole regexp bigger, but makes the code easier to read and you avoid the extra logic to handle different cases. To generate a hash with both versions from you current hash, just use:
filter = Hash[*filter.map { |k, v| [[k,v], [k.capitalize,v.capitalize]] }.flatten]

How not to order a list of pk's in a query?

I have a list of pk's and I would like to get the result in the same order that my list is defined... But the order of the elements is begging changed. How any one help me?
print list_ids
[31189, 31191, 31327, 31406, 31352, 31395, 31309, 30071, 31434, 31435]
obj_opor=Opor.objects.in_bulk(list_ids).values()
for o in obj_oportunidades:
print o
31395 31435 31434 30071 31309 31406 31189 31191 31352 31327
This object should be used in template to show some results to the user... But how you can see, the order is different from the original list_ids
Would have been nice to have this feature in SQL - sorting by a known list of values.
Instead, what you could do is:
obj_oportunidades=Opor.objects.in_bulk(list_ids).values()
all_opor = []
for o in obj_oportunidades:
print o
all_opor.append(o)
for i in list_ids:
if i in all_opor:
print all_opor.index(i)
Downside is that you have to get all the result rows first and store them before getting them in the order you want. (all_opor could be a dictionary above, with the table records stored in the values and the PKeys as dict keys.)
Other way, create a temp table with (Sort_Order, Pkey) and add that to the query:
Sort_Order PKey
1 31189
2 31191
...
So when you sort on Sort_Order and Opor.objects, you'll get Pkeys it in the order you specify.
I found a solution in: http://davedash.com/2010/02/11/retrieving-elements-in-a-specific-order-in-django-and-mysql/ it's suited me perfectly.
ids = [a_list, of, ordered, ids]
addons = Addon.objects.filter(id__in=ids).extra(
select={'manual': 'FIELD(id,%s)' % ','.join(map(str,ids))},
order_by=['manual'])
This code do something similiar to MySQL "ORDER BY FIELD".
This guy: http://blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html
Solved the problem for both MySQL and PostgreSQL!
If you are using PostgreSQL go to that page.