Replacing rails model object key with ruby hash value - ruby-on-rails

I have a rails model object as shown below
[#<Object id: 876, input_type: 4, require_level: true>,#<Object id: 877, input_type: 4, require_level: true>, #<Object id: 878, input_type: 2, require_level: true>]
Input_types is a hash as shown below
input_types = {"w"=>1, "x"=>2, "y"=>3, "z"=>4}
I would like to get output as follows based on the input_type attribute replacement
[#<Object id: 876, input_type: 4, require_level: true>,#<Object id: 877, input_type: 4, require_level: true>, #<Object id: 878, input_type: 2, require_level: true>]
I have the following code:
objects.each do |object|
replacement_key = input_types.key(object.input_type)
object.attributes["input_type"] = replacement_key
end
This does not produce any result and return the object as it is in the initial stage

Try this one
new_objects = objects.map do |object|
replacement_key = input_types.key(object.input_type)
object.input_type = replacement_key
object
end.as_json

This works out. Any better ways without json?
objects = objects.as_json
objects.each do |object|
replacement_key = input_types.key(object["input_type"])
object["input_type"] = replacement_key
end

Related

How to use the PostgreSQL JSON array query ActiveRecord::Relation in Ruby on Rails

I want to query ActiveRecord::Relation with 51 fields.
the data structure is like this:
matings: {"ids"=>[50, 51, 64]}
or
matings: {"ids"=>51}
If I do:
MouseColony.where("CAST(matings AS TEXT) LIKE ?", "%51%")
=>#<ActiveRecord::Relation [
#<MouseColony id: 604, animal_no: "a0008", animal_desc: "", gender: "M♂", source: "外购", animal_status: "配对", cage_id: nil, generation: 0, birth_date: "2018-12-25", weaning_date: "2019-01-15", disable_date: nil, received_date: "2019-03-20", created_at: "2019-06-03 02:45:03", updated_at: "2019-06-03 03:14:37", user_id: 1, strain_id: 1, mating_id: 64, litter_id: nil, purchase_mouse_number: "17203", age: 223, mating_quantity: 3, matings: {"ids"=>[50, 51, 64]}, genotype_id: 10, experiment_id: nil, experiment_date: nil, age_weeks: 32>,
#<MouseColony id: 624, animal_no: "a0028", animal_desc: "", gender: "F♀", source: "外购", animal_status: "配对", cage_id: nil, generation: 0, birth_date: "2018-12-25", weaning_date: "2019-01-15", disable_date: nil, received_date: "2019-03-20", created_at: "2019-06-03 02:50:07", updated_at: "2019-06-03 03:09:11", user_id: 1, strain_id: 1, mating_id: 51, litter_id: nil, purchase_mouse_number: "17138", age: 223, mating_quantity: 5, matings: {"ids"=>51}, genotype_id: 9, experiment_id: nil, experiment_date: nil, age_weeks: 32>
]>
I tried to use MouseColony.where("CAST(matings ->> 'ids' AS TEXT) LIKE ?", "%51%") or using MouseColony.where("matings ->> 'ids' = ?", "51"), but the result is such a MouseColony Load (1.0ms) SELECT "mouse_colonies".* FROM "mouse_colonies" WHERE (CAST(matings ->> 'ids' AS TEXT) LIKE '%51%') LIMIT $1 [["LIMIT", 11]]
=> #<ActiveRecord::Relation []>
I've also tried to use this:
MouseColony.where("matings #>> '{ids}' = ?", "51")
But still can't find any data.
I think my problem might be here:
My models: mouse_colony.rb
store :matings, :accessors => [:ids], coder: JSON
and I storage record like this:
#mouse_colony.matings[:ids] = [50, 51, 64]`` #mouse_colony.save
You can try using the "contains" operator #>:
MouseColony.where("matings->'ids' #> '?'", 51)
You should be able to use the LIKE operator like this:
MouseColony.where("matings::json->>'ids' LIKE ?", "%51%")

Convert to hash - Ruby on rails

I have this extracted from a table
#<Section id: 12, name: "Seccion 1", created_at: "2018-07-24 15:06:34", updated_at: "2018-07-24 15:06:34", quotation_id: 62, order: 0>
but I want to convert it to hash
name_seccions.each do | section |
section.quotation_id = event_current
#Convert to hash
puts section.inspect
end
section_hash = section.attributes

How to make hash with given values in rails

I have included given code
#marks= Mark.all
which gives me this
#<ActiveRecord::Relation [#<Mark id: 1, name: "xyz", number: 20>, #<Mark id: 2, name: "abc", number: 25>, #<Mark id: 3, name: "toy", number: 40>, #<Mark id: 4, name: "tim", number: 35>, #<Mark id: 5, name: "vim", number: 45>]>
Now I want to make a new hash of marks i.e {1=>"xyz", 2=>"abc", 3=>"toy", 4=>"tim", 5=>"vim"}. Please guide me how to obtain this thanks in advance.
try this
#marks = Mark.all
#hashed_marks = Hash[#marks.collect{|v| [ v.id, v.name ] }]
#marks = Mark.all
#hashed_marks = Hash[#marks.pluck(:id, :name)]
You can do
#marks = Mark.all
marks_hash = {}
#marks.each do |mark|
marks_hash.merge( mark.attributes )
end
marks_hash
Another way you can do it is:
#marks.as_json
If you change your marks code to use pluck
#marks = Mark.pluck(:id, :name)
You will then just get a multi dimensional array
[[1, "xyz"], [2, "abc"]]
Then you can just do
#hash = Hash[#marks] => {1=>"xyz", 2=>"abc"}
Try this:
my_hash = Hash.new
Mark.all.each{|m| my_hash[m.id] = m.name }
Or
If you are using Rails 4 then use pluck and to_h
my_hash = Mark.pluck(:id, :name).to_h

Rails how to calculate multiple sums from one query data

With the following two models, Company and Response, I am making a query of the total responses per company like this:
#allResponses = Company.find(current_user_company_id).responses
this gives me data like this:
[#<Response id: 1, company_id: 1, created_at: "2013-04-24 02:36:54", feedback_score: 10, feedback_explanation: "I really like the way you guys do xyz.", additional_data: "", updated_at: "2013-04-24 02:36:54">, #<Response id: 2, company_id: 1, created_at: "2013-04-25 03:51:07", feedback_score: 5, feedback_explanation: "customer service is spotty.", additional_data: "", updated_at: "2013-04-25 03:51:07">, #<Response id: 3, company_id: 1, created_at: "2013-04-25 03:52:04", feedback_score: 7, feedback_explanation: "You've got potential.", additional_data: "", updated_at: "2013-04-25 03:52:04">, #<Response id: 4, company_id: 1, created_at: "2013-04-25 03:52:18", feedback_score: 9, feedback_explanation: "Almost perfect.", additional_data: "", updated_at: "2013-04-25 03:52:18">]
I want to get the following two variables out of this data:
#sumOfHighScores = some.thing.here #sum of feedback_scores that are greater than 8
#sumOfLowScores = some.thing.here.too #sum of feedback_scores that are less than 7
You can try this,
#sumOfHighScores = #allResponses.select{ |response| response.feedback_score > 8 }.map(&:feedback_score).sum
#sumOfLowScores = #allResponses.select{ |response| response.feedback_score < 7 }.map(&:feedback_score).sum
Try this..
#sumOfHighScores = #allResponses.select{ |response| response.feedback_score > 8 }.sum
#sumOfLowScores = #allResponses.select{ |response| response.feedback_score < 7 }.sum
I will perform the entire calculation in the database.
company = Company.find(current_user_company_id)
totals = company.responses.sum(
:feedback_score,
:group => "CASE WHEN feedback_score < 7 THEN 'low' ELSE 'high' END")
low, high = (totals['low'] || 0), (totals['high'] || 0 )

Unexpected behaviour of array.count in ruby

Hi i am using Rails3 when i puts array of subscribers like this
#subscribers = User.all
and puts it.gives me this array
[#<User id: 62, is_activated: true, subscriber: "TEST_DB2", ports_order: 100, created_at: "2012-05-21 14:47:48">, #<User id: 66, is_activated: true, subscriber: "JOHI", ports_order: 100, created_at: "2012-05-22 12:06:19">, #<User id: 68, is_activated: true, subscriber: "ALI-NAQWI", ports_order: 100, created_at: "2012-05-24 11:01:22">]
And when i give command
#subscribers.count #it give me 0 count
Why?????????
Try length instead, it can be a bug in AREL :)
That he is trying to lazy do something. He is giving back proxy object so it can be a problem there. Length will always work on your result value ~ array.

Resources