Creating a where query in rails from an array - ruby-on-rails

I need to make a where query from an array where each member of the array is a 'like' operation that is ANDed. Example:
SELECT ... WHERE property like '%something%' AND property like '%somethingelse%' AND ...
It's easy enough to do using the ActiveRecord where function but I'm unsure how to sanitize it first. I obviously can't just create a string and stuff it in the where function, but there doesn't seem to be a way possible using the ?.
Thanks

The easiest way to build your LIKE patterns is string interpolation:
where('property like ?', "%#{str}%")
and if you have all your strings in an array then you can use ActiveRecord's query chaining and inject to build your final query:
a = %w[your strings go here]
q = a.inject(YourModel) { |q, str| q.where('property like ?', "%#{str}%") }
Then you can q.all or q.limit(11) or whatever you need to do to get your final result.
Here's a quick tutorial on how this works; you should review the Active Record Query Interface Guide and the Enumerable documentation as well.
If you had two things (a and b) to match, you could do this:
q = Model.where('p like ?', "%#{a}%").where('p like ?', "%#{b}%")
The where method returns an object that supports all the usual query methods so you can chain calls as M.where(...).where(...)... as needed; the other query methods (such as order, limit, ...) return the same sort of object so you can chain those as well:
M.where(...).limit(11).where(...).order(...)
You have an array of things to LIKE against and you want to apply where to the model class, then apply where to what that returns, then again until you've used up your array. Thing that look like a feedback loop tend to call for inject (AKA reduce from "map-reduce" fame):
inject(initial) {| memo, obj | block } → obj
Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.
If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element [...] the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.
So inject takes the block's output (which is the return value of where in our case) and feeds that as an input to the next execution of the block. If you have an array and you inject on it:
a = [1, 2, 3]
r = a.inject(init) { |memo, n| memo.m(n) }
then that's the same as this:
r = init.m(1).m(2).m(3)
Or, in pseudocode:
r = init
for n in a
r = r.m(n)

If you're using AR, do something like Model.where(property: your_array) , or Model.where("property in (?)", your_array) This way, everything is sanitized

Let's say your array is model_array, try Array select:
model_array.select{|a|a.property=~/something/ and a.property=~/somethingelse/}
Of course you can use any regex as you like.

Related

Ruby Calling Join on an Array versus String

I have a script that creates an array , then adds items to the array depending on certain circumstances. In most cases, the array will end up with several values inside of it. Occasionally, the array will only hold one value inside of it.
After preparing this array, I usually call .join(",") to create a comma-separated string of all the array values:
tags.join(",")
It works fine when the array has multiple values, but when it only has one value it throws an error:
NoMethodError: undefined method 'join' for "Whatever the array value": String
Any idea why this is? What is the easiest way to resolve this? Do I need to do an if statement to check if the variable is an array or string? Seems a bit silly...let me know if I am missing something here.
If obj is your object, you can write
[*obj].join
For example
arr = ["Fa", "bu", "lo", "us!"]
[*arr].join #=> "Fabulous!"
str = "Whoa!"
[*str].join #=> "Whoa!"
This works because
[*arr] #=> ["Fa", "bu", "lo", "us!"] == arr
[*str] #=> ["Whoa!"]
Similarly,
[*[1,2,3]].join #=> "123"
[*7].join #=> "7"
You can use join on an array as following way :
#array = ["this","is","join","method","example"]
#array.join(" ")
"this is join method example"
#array.join("_")
"this_is_join_method_example"
In the case of a single element (say, 'Hello'), you should be calling join on an array, not the string itself; for example, ['Hello'].join(",") rather than 'Hello'.join(","). Of course, if there's only one element join doesn't actually do anything, so you could just use a conditional if to skip it... but that's kinda ugly. Most of the time, I'd use the construction Array(tags).join(","). If passed a single string, that'll wrap it in an array; if passed an array, it's a noop, returning the array as-is.

ActiveRecord Integer Column won't accept some Integer assignments

I'm seeing some genuinely bizarre behavior w/ ActiveRecord as it relates to assignment. I have an ActiveRecord model named Venue that includes the measurements of the Venue, all integers less than 1K. We add Venues via an XML feed. On the model itself, I have a Venue.from_xml_feed method takes the XML, parses, and creates Venues.
The problem comes from the measurements. Using Nokogiri, I'm parsing out the measurements like so:
elems = xml.xpath("//*[#id]")
elems.each do |node|
distance = node.css("distances")
rs = distance.attr("rs")
// get the rest of the sides
# using new instead of create to print right_side, behavior is the same
venue = Venue.new right_side: rs # etc
venue.save
puts venue.right_side
end
The problem is that venue.right_side ALWAYS evaluates to nil, even though distance.attr("rs") contains a legal value, say 400. So this code:
rs = distance.attr("rs")
puts rs
Venue.new right_side: rs
Will print 400, then save rs as nil. If I try any type of Type Conversions, like so:
content = distance.attr("rs").content
str = content.to_s
int = Integer(str)
puts "Is int and Integer? #{int.is_a? Integer}"
Venue.new right_side: int
It will print Is int an Integer? true, then again save again save Venue.right_side as nil.
However, if I just explicitly create a random integer like so:
int = 400
Venue.new right_side: int
It will save Venue.right_side as 400. Can anyone tell me what's going on with this?
Well, you failed to include the prerequisite sample XML to confirm this, so you get a fairly generic answer.
In your code you're using:
distance = node.css("distances")
rs = distance.attr("rs")
css doesn't return what you think it does. It returns a NodeSet, which is similar to an Array. When you try to use attr on a NodeSet, you're going to set the value, not retrieve it. From the documentation:
#attr(key, value = nil, &blk) ⇒ Object (also: #set, #attribute)
Set the attribute key to value or the return value of blk on all Node objects in the NodeSet.
Because you're not using a value, the resulting action is to remove the attribute from the tag, which will then return nil and Ruby will assign nil to rs.
If you want to get the attribute of a node, you need to point to the node itself, so use at, or at_css, either of which returns a Node. Once you have the node, you can use attribute to retrieve the value, or use the [] shortcut similar to this untested code:
rs = node.at('distances')['rs']
Again though, because you didn't supply XML it's not possible to tell what else you might be trying to do, or whether this code is entirely accurate.

How do I cleanly map / sort / fold / sort / expand using only cascades or chained calls, in Dart?

I would like to perform the following operations on a source list:
map
toList
sort
fold
sort
expand
toList
Some of these methods, like map and toList are chainable, because they return a non-null object. However, the sort method returns void as it operates on a List and does not return a list.
Dart has a method cascade operator, which works great for method calls that do not return this or another object.
I'm having a hard time writing the above sequence of calls without resorting to assigning a variable after the sort and then starting the chain of calls again.
I'd like to write the equivalent of:
return thing
.map(...)
.toList()
.sort(...)
.fold(...)
.sort(...)
.expand(...)
.toList();
The closest I can get is:
var thing
.map(...)
.toList()
..sort(...);
var otherThing = thing
.fold(...)
..sort(...);
var finalThing = otherThing.expand(...).toList();
Is there a better way? How do I "break out" of the cascade and continue on a chain?
Can you add some parens? I guess something like this...
return ((thing
.map(...)
.toList()..sort(...))
.fold(...)..sort(...))
.expand(...)
.toList();

Read tuple key and value

How can I read a tuple key and value in Erlang?
I have this variable:
Params = [<<"TPUIBrowser">>,0,18,
{[{<<"End">>,<<"location-1ÿ">>},{<<"Start">>,<<"location-1">>}]},
null]
and I would like to get the values for <<"End">> and <<"Start">>.
How could I do that in Erlang?
I can do it like this:
[_,_,_,A,_] = Params.
{[{_,B},{_,C}]} = A.
But this feels very verbose and error prone (i.e. when I get sent more params). What would be the best erlang way?
There are functions for this in the lists library. Check out lists:keyfind:
[_,_,_,{A},_] = Params,
{Key, Value} = lists:keyfind(<<"End">>, 1, A).
(I assume you know where in Params you have A)
Alternatively you can use records which are particularly suitable if you plan to add more fields.
Since you use a list here {[{_,B},{_,C}]} = A. I assume that there might be more elements; in this case, making a recursive function to unpack it could be better.

Manipulate elements of arrays dynamically without for loop in ruby

I have an array in ruby and i want to change the values of it's elements dynamically depending on a particular attribute. Suppose i have an array,
array = [123,134,145,515]
And i want to manipulate this elements like getting all the elements multiplied by a parameter, how can i get it done without having to do it explicitly each time using for loop?
Are you looking for this:
array = [123,134,145,515]
n = <any number>
array1 =array.map{|a| a * n}
or
array.map!{|a| a * n} #which modify the array object itself
For this, you can use something like the collect method in ruby for arrays.
You can write a method which can be called whenever required passing the array and parameter as argument.
For instance you can write a method similar to this ;
array = [123,134,145,515]
parameter_value = 2
Now, depending on the requirement you can define a method like this :
array.collect {|x| x * parameter_value}
In this case, this would return an array similar to this :
array = [246, 268, 290, 1030]

Resources