Update Each Array-Object Value in Rails - ruby-on-rails

Basically I want to update each table column for a Model in Rails 5.
str = "abc---def"
str.split('---').map do |a|
Foo.where(product_id:1).update_all(bar: a)
end
Old object would be like:
[
[0] { product_id: 1,
...,
bar: "xxx",
...
},
[1] { product_id: 1,
...,
bar: "xxx",
...
}
]
New should be like:
[
[0] { product_id: 1,
...,
bar: "abc",
...
},
[1] { product_id: 1,
...,
bar: "def",
...
}
]
But what I got is bar: "def" for each. Is there a clean method in rails to achieve what I want? update_attributes gives an error.
Is the title name correct?

First of all let's get started from some basics.
You want to update multiple rows and want to set different value for each row. So it cannot be done in single query like you are doing. So you need to loop through the Foo objects and set each one separately.
So let's assume
str = "abc---def---ghi---jkl"
tokens = str.split('---')
foos_to_update = Foo.where(product_id: 1) #Let's assume it will return 4 or lesser records. (otherwise you need to tell what do you wanna do if it returns more then `tokens`)
foos_to_update.each_with_index {|foo,i| foo.update(bar: tokens[i])}
The last line is looping through returned objects and setting the bar value for each object.

First of all, using Foo.where(id:1).update_all to update a single record may work, but is non-idiomatic. It's better to use Foo.find_by(id: 1).update. For getting single records, I prefer to use find_by instead of find because it returns nil instead of raising NotFound errors, but that's a personal preference.
Second, the way you're using update_all(bar: a) is giving you unexpected results. In a map block, the returned value becomes part of the resulting array. update_all doesn't return the record which were changed. It returns an integer showing the count of records which were changed. Similarly, update doesn't return the record. It returns true or false` depending on if the validations passed.
Tying together these concepts, the following code can be written:
str = "abc---def"
str.split('---').map do |a|
foo = Foo.find_by(id:1)
foo&.update(bar: a)
foo
end
# note that you could instead write `foo.update(bar: a)` if you
# don't want to use the safe navigation operator
Or another way to write it which does the same thing:
str = "abc---def"
str.split('---').map do |a|
Foo.find_by(id:1)&.tap { |foo| foo.update(bar: a) }
end
Note that in these examples I'm using the safe navigation operator which is in Ruby versions newer than 2.3. It helps prevent NoMethodError on nil objects, but isn't really necessary.

Related

Rails - Accessing JSON members

I am new to Rails, and working with some JSON, and not sure how to get to the data as the examples below:
1) If i were to use JSON.parse(response)['Response']['test']['data']['123456'], i will need to parse another response for 123457, is there a better way to loop through all the objects in data?
2) base on the membershipId, identify the top level object, ie data.
"test": {
"data": {
"123456": {
"membershipId": "321321312",
"membershipType": a,
},
"123457": {
"membershipId": "321321312",
"membershipType": a,
},
}
JSON.parse(response)['Response']['test']['data'].each do |key, object|
puts key
puts object['membershipID']
...
end
To select the data record associated with a particular membership
match_membership = '321321312'
member = JSON.parse(response)['Response']['test']['data'].select |_key, object|
object['membershipID'] == match_membership
end
puts member.key
=> 123456
For 1:
Assumption:
By you saying "need to parse another response", you were doing something like below:
# bad code: because you are parsing `response` multiple times
JSON.parse(response)['Response']['test']['data']['123456']
JSON.parse(response)['Response']['test']['data']['123457']
then simply:
Solution 1:
If you are gonna be accessing 2+ level deep hash values for just maybe 2 or 3 times,
response_hash = JSON.parse(response)
response_hash['Response']['test']['data']['123456']
response_hash['Response']['test']['data']['123457']
Solution 2:
If you are gonna be accessing 2+ level deep hash values for loooooots of times,
response_hash = JSON.parse(response)
response_hash_response_test_data = response_hash['Response']['test']['data']
response_hash_response_test_data['123456']
response_hash_response_test_data['123457']
response_hash_response_test_data['123458']
response_hash_response_test_data['123459']
response_hash_response_test_data['123460']
# ...
Solution 2 is better than Solution 1 because it saves repetitive method calls for Hash#[] which is the "getter" method each time you do like ...['test'] then ['data'] then ['123456'], and so is better-off doing Solution 2 which you store the nested-level of the hash into a variable (this does not duplicate the values in-memory!). Plus it's more readable this way.

Clone constant of hash into new variable without mutating constant on update with .each block?

I'm struggling with something. I've abstracted my code out to be as simple as possible, yet I still don't understand why it's having this behaviour.
I'm creating a constant consisting of a set of key-value pairs and freezing it. I'm then using the .dup method to copy the hash into a new variable.
However, when I iterate over an array and try to store it in the (previously empty) array in the new variable, it not only updates the new variable, but also the original constant. This only seems to be the case with the .each method - if I pass the new values directly as a new array, it works without updating the constant.
My abstracted code is below:
CONFIG_VALUES = { results: [], loop_count: 0 }.freeze
the_results = ["foo", "bar"]
abc = CONFIG_VALUES.dup
the_results.each do |res|
abc[:results] << res
end
abc
#=> {:results=>["foo", "bar"], :loop_count=>0}
CONFIG_VALUES
#=> {:results=>["foo", "bar"], :loop_count=>0}
Hash#dup method isn't recursive. Anyway, if you use Ruby on Rails, and I think you do since you tagged it, you can use #deep_dup method: http://api.rubyonrails.org/classes/Hash.html#method-i-deep_dup
It's an ActiveSupport method, so you could just use the gem in case you aren't using Ruby on Rails.
You can achieve the desired result with:
CONFIG_VALUES = { results: [], loop_count: 0 }.freeze
the_results = %w[foo bar]
abc = CONFIG_VALUES.merge(results: the_results)
abc
#=> {:results=>["foo", "bar"], :loop_count=>0}
CONFIG_VALUES
#=> {:results=>[], :loop_count=>0}
As I understand it, this works because #merge does not mutate CONFIG_VALUES and you are essentially creating an entirely new set of objects.

DynamoDB contains value in an array using rails

I'm studying DynamoDB using rails and I got a doubt.
I not be able to find a solution on web, so If you can solve it I'll thank.
The doubt is how can I find values into array saved on a table, for example:
I have a lot of data in my_table where there are fields called "numbers" that are arrays like:
[1,2,3,4]
[3,4,5,6]
[1,3,4,7]
[4,7,8,10]
[8,9,12,14]
[12,14,16,20]
So, I want select all entries that contains numbers 1,3,4. In this case four results.
So, my code is
result = dynamodb.scan({
table_name: "my_table",
select: "ALL_ATTRIBUTES",
attributes_to_get: ["numbers"],
scan_filter: {
"numbers" => {
attribute_value_list: [1,3,4],
comparison_operator: "CONTAINS"
}
}
})
But I get this error: One or more parameter values were invalid: Invalid number of argument(s) for the CONTAINS ComparisonOperator
How can I do this action using dynamo DB?
Thanks a lot
Try this and let me know if it works, I know from experience that DynamoDB is very painful to filter.
result = dynamodb.scan(
table_name: 'my_table',
expression_attribute_values: {
':one' => 1,
':two' => 2,
':three' => 3,
':four' => 4
},
filter_expression: 'contains(numbers, :one) OR contains(numbers, :two) OR contains(numbers, :three) OR contains(numbers, :four)'
)
I can't think of anything simpler currently, the method you linked is marked as deprecated, instead you should use expression_attribute_values and filter_expression.

Ruby, accessing a nested value in a hash

I have the following hash. Using ruby, I want to get the value of "runs". I can't figure out how to do it. If I do my_hash['entries'], I can dig down that far. If I take that value and dig down lower, I get this error:
no implicit conversion of String into Integer:
{"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588, ...
Assuming that you want to lookup values by id, Array#detect comes to the rescue:
h = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]}]}
# ⇓⇓⇓⇓⇓⇓⇓ lookup element with id = 7
h['entries'].detect { |e| e['id'] == 7 }['runs']
.detect { |e| e['id'] == 2588 }
#⇒ { "id" => 2588 }
As you have an array inside the entries so you can access it using an index like this:
my_hash["entries"][0]["runs"]
You need to follow the same for accessing values inside the runs as it is also an array.
Hope this helps.
I'm not sure about your hash, as it's incomplete. So , guessing you have multiple run values like:
hash = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]},
{"id"=>"8", "runs"=>[{"id"=>2589}]},
{"id"=>"9", "runs"=>[{"id"=>2590}]}]}
Then, you can do
hash["entries"].map{|entry| entry["runs"]}
OUTPUT
[[{"id"=>2588}], [{"id"=>2589}], [{"id"=>2590}]]

What kind of ruby method call is Array(x)

What is the meaning, and where is the Ruby documentation for the syntax of:
Array(phrases)
which I found browsing the Rails source here:
# File actionpack/lib/action_view/helpers/text_helper.rb, line 109
...
119: match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
I thought that Array.new would normally be used to create an array, so something different must be going on here. BTW from the context around this code, the phrases variable can be either a string or an array of strings.
It's most likely the Kernel#Array method, see here. It's slightly different than Array.new; it's more of a cast into an array. (It tries to_ary and to_a.)
Array(x) appears to act exactly the same as x.to_a.
#Brian is right - it's a method of Kernel. Pickaxe says:
Array( arg ) -> anArray
Returns arg .to_a.
Array(1..5) » [1, 2, 3, 4, 5]
It's the Kernel#Array method, as others have already stated.
But the Ruby documentation does not give credit to this method's usefulness in simplifying your code. Also it does not tell you that objects which don't have a to_ary or a to_a method are encapsulated in an array.
Array([1,2,3]) -> [1,2,3]
Array(1..3) -> [1,2,3]
Array({ a: 1, b: 2 }) -> [[:a, 1],[:b,2]]
Array("Hello World") -> ["Hello World"]
Array(1) -> [1]
All these features of Kernel#Array allow you to handle typical corner cases with parameters in one single line.
See this code, which is a typical situation in many APIs or DSLs:
# data can be nil, a single value or an array
def handle(data)
data ||= Array.new #Case 1: Data is nil
data = [data] unless data.is_a?(Array) #Case 2: Data is a single value
data.each { |d| ... }
end
This can be simplified by using Kernel#Array:
def handle(data)
Array(data).each { |d| ... }
end
Of course one has to be careful with providing different types for the data parameter, because the to_ary/to_a methods might or might not give you what you expect.

Resources