Convert ActiveRecord::Relation into a usable array - ruby-on-rails

When I call:
preivous_lessons = #item.where("track_id = ?", lesson.track_id)
I get this active record realtion:
[#<CodeLesson id: 2, name: "Python", permalink: "python", lesson_content: "", instructions: "Print your name to the console.", hints: "", starting_code: "\"\"\"\r\nThis is a comment\r\n\"\"\"\r\n\r\nprint(\"Hello, World\"...", language_id: "12", order: 1, track_id: 2, user_id: 1, created_at: "2014-02-14 16:01:12", updated_at: "2014-02-15 21:14:43", visible: true>, #<CodeLesson id: 8, name: "Test Lesson", permalink: "test-lesson", lesson_content: nil, instructions: nil, hints: nil, starting_code: nil, language_id: "26", order: nil, track_id: 2, user_id: 1, created_at: "2014-02-20 19:23:15", updated_at: "2014-02-20 19:23:15", visible: false>]
How do I convert this into a usable array of models so I can do something like this:
preivous_lessons.each do |i|
highest = i.order if i.order > highest
end

As OP confirmed from my comment, that my hint solved his problem, I am putting it as an answer to the post :
preivous_lessons = #item.where("track_id = ?", lesson.track_id)
highest = preivous_lessons.maximum(:order)
Documentation of maximum :
Calculates the maximum value on a given column. The value is returned with the same data type of the column, or nil if there's no row.

preivous_lessons = #item.where("track_id = ?", lesson.track_id).all

Related

Globalize duplicated locales

When I create a new admin user, there are three objects of translations:
Admin.last.translations.map(&:locale) # => [:ru, :uz, :uz]
Why are the locales duplicated?
Example:
admin.position_uz = 'CTO'
admin.position_ru = 'CTO'
admin.save!
admin.translations.count = 3
admin.translations.first.position = 'CTO'
admin.translations.second.position = 'Another value or empty'
admin.translations.third.position = 'CTO'
Every time the locale is set to uz, it shows the second variant.
Admin translations loo like
[
#<Admin::Translation id: 1, admin_id: 2, locale: "ru", position: "CTO", created_at: "2019-01-16 06:24:17", updated_at: "2019-01-16 06:30:31">,
#<Admin::Translation id: 2, admin_id: 2, locale: "uz", position: "Board Member", created_at: "2015-07-26 20:42:18", updated_at: "2015-07-26 20:42:18">,
#<Admin::Translation id: 3, admin_id: 2, locale: "uz", position: "CS manager", created_at: "2019-01-16 06:24:17", updated_at: "2019-01-16 07:09:21">
]

Finding a value inside an array

I am stuck with an issue, any help would be appreciated.
I have a rails query
array = Issue.where("tracker_id =? AND project_id = ?",8,140).first.custom_field_values
This returns an array like this :
[#<CustomFieldValue:0x000000074d8b98 #custom_field=#<IssueCustomField id: 4, type: "IssueCustomField", name: "Phase Injected", field_format: "list", possible_values: ["Planning", "Requirements", "Design", "Coding", "Testing"], regexp: "", min_length: nil, max_length: nil, is_required: true, is_for_all: true, is_filter: true, position: 4, searchable: false, default_value: "", editable: true, visible: true, multiple: false, format_store: {"url_pattern"=>"", "edit_tag_style"=>""}, description: "", formula: nil, is_computed: false>, #customized=#<Issue id: 43, tracker_id: 8, project_id: 140, subject: "Cost of rework is not calculated for past sprints", description: "", due_date: nil, category_id: nil, status_id: 1, assigned_to_id: 5, priority_id: 2, fixed_version_id: 1, author_id: 8, lock_version: 3, created_on: "2018-07-26 05:40:19", updated_on: "2018-08-09 10:46:12", start_date: "2018-07-26", done_ratio: 0, estimated_hours: nil, parent_id: 42, root_id: 42, lft: 2, rgt: 3, is_private: false, closed_on: nil, sprint_id: nil, position: nil>, #value="Planning", #value_was="Planning">,.....]
The above array has more then 10 results pasted the first one.
How do I search inside this array for the name = 'Phase Injected' and get the result that is #value which is 'planning'.
Currently I am trying to go inside the array by:
<% array.each do |cf| %>
<% if cf.custom_field.name = "Phase Injected" %>
<%= cf %> #this returns #value
<% end %>
<% end %>
can I not do array.find_by_something and get the value?
Thanks
It returns the active record relation object, not the array in the first place. Yes, it quacks as an array, though.
You should filter the data directly in the database instead of an extremely ineffective array filtering:
Issue.
joins(:issue_custom_fields).
where(tracker_id: 8, project_id: 140).
where('`issue_custom_fields`.`name` = "Phase Injected"')
or, as #Stefan suggests in comments:
Issue.
joins(:issue_custom_fields).
where(tracker_id: 8, project_id: 140).
where(issue_custom_fields: { name: 'Phase Injected' })

Search in jsonb and array combination in postgres with rails4 stored_accessor

I have a model called Event, where I have stored_accessor "list" (stored like data: {"list"=>[{"key"=>"key1", "value"=>"value1"}]}).
I need to make a search query o
#<Event id: "1", title: "HHHH", description: nil, data: {"list"=>[{"key"=>"key1", "value"=>"value1"}, {"key"=>"key2", "value"=>"value2"}]}, created_at: "2017-04-14 21:06:22", updated_at: "2017-04-20 10:36:08">
#<Event id: "2", title: "HHHH", description: nil, data: {"list"=>[{"key"=>"key1", "value"=>"value1"}]}, created_at: "2017-04-14 21:06:22", updated_at: "2017-04-20 10:36:08">
#<Event id: "3", title: "HHHH", description: nil, data: {"list"=>[{"key"=>"key11", "value"=>"value11"}, {"key"=>"key12", "value"=>"value12"}]}, created_at: "2017-04-14 21:07:22", updated_at: "2017-04-20 10:37:08">
#<Event id: "4", title: "HHHH", description: nil, data: {"list"=>[{"key"=>"key111", "value"=>"value111"}, {"key"=>"key112", "value"=>"value112"}]}, created_at: "2017-04-14 21:08:22", updated_at: "2017-04-20 10:38:08">
I have a serach params like
1) {'key'=> 'key1', 'value'=> 'value1'}
2) ["key"=>"key1", "value"=>"value1"}, {"key"=>"key2", "value"=>"value2"}]
In first case, it should return Event id 1 and 2.
In second case, it should return Event id 1. (event if return 1 and 2 both could be acceptable).
I am not sure with json and array combination.
Please help.
You may do it with PostgreSQL jsonb's operator #>. Also you need to write the full path for search params: {'list' => [{'key'=> 'key1', 'value'=> 'value1'}]}. Try this code:
to_contain1 = {'list' => [{'key'=> 'key1', 'value'=> 'value1'}]}
to_contain2 = {'list' => [{'key'=> 'key2', 'value'=> 'value2'}]}
Event.
where("data #> ?", to_contain1.to_json})
# returns events 1 & 2
Event.
where("data #> ?", to_contain1.to_json).
where("data #> ?", to_contain2.to_json)
# returns event 1

Check if a value created_at not equal to current date exists in an array in Ruby

I have a collection of user.paid_subscriptions in which each subscription has attributes created_at(datetime) and active(boolean).
How can I check if a PaidSubscription exists such that created_at is not equal to a certain date and active is true?
PaidSubscription looks like this:
[
#<PaidSubscription id: 11457,
user_id: 12,
period: 3,
price: 4000,
expires_at: "2016-03-08 09:44:56",
expires_at: "2016-03-08 09:44:56",
created_at: "2015-12-08 09:44:56",
updated_at: "2016-03-08 23:00:09",
active: false,
giver_id: 20573,
partial: false,
remaining_days: 0>,
#<PaidSubscription id: 13948,
user_id: 12,
period: 1,
price: 1500,
expires_at: "2016-04-11 12:07:40",
created_at: "2016-03-11 13:07:40",
updated_at: "2016-04-11 22:00:11",
active: false,
giver_id: nil,
partial: false,
remaining_days: 0>,
#<PaidSubscription id: 11458....
]
Try this,
If it is a query then it should be like this
user.paid_subscriptions.where("created_at < :date or created_at > :date and active = :active",{date: DateTime.civil(yyyy,mm,dd), active: true})
Or
if it is an array you can use it like below.
user.paid_subscriptions.any? {|ps| ps.active && ( ps.created_at.to_date < Date.civil(yyyy, mm, dd) || ps.created_at.to_date > Date.civil(yyyy, mm, dd))}

Ruby change type in array of hashes from float to integer

I have such array data:
[#<PriceList id: 463134, distributor_id: 6, brand: "Mann-filter", article_nr: "W712/22", price: 5405.0, quantity: "50", waittime: 1, description: "Фильтр масл OPEL 1.2-3.0L (OC90)", created_at: "2013-01-30 16:35:34", updated_at: "2013-01-30 16:35:34", art_group: "Фильтр масл OPEL 1.2-3.0L (OC90)", oem_number: nil>, #<PriceList id: 517164, distributor_id: 6, brand: "Mann-filter", article_nr: "W712/22", price: 5442.0, quantity: "500", waittime: 3, description: "Фильтр масляный OPEL/GM/DAEWOO", created_at: "2013-01-30 16:42:26", updated_at: "2013-01-30 16:42:26", art_group: "Фильтр масляный OPEL/GM/DAEWOO", oem_number: nil>, #<PriceList id: 463135, distributor_id: 6, brand: "Mann-filter", article_nr: "W712/22(10)", price: 5101.0, quantity: "20", waittime: 1, description: "Фильтр масл.без упак.OPEL/GM (OC90Of)", created_at: "2013-01-30 16:35:34", updated_at: "2013-01-30 16:35:34", art_group: "Фильтр масл.без упак.OPEL/GM (OC90Of)", oem_number: nil>, ... etc
how can i change price type?
i try
#non_original2 = #non_original2.map { |e| e[:price].to_i }
but as result i see only price values... How can i change my array, so that price field in all hashes become integer value?
what about
#non_original2.each { |e| e[:price] = e[:price].to_i }
This changes every PriceList item in the list (and does not copy the list).
Using your approach results in a list of price values, because map collects the result of the block. The result of e[:price].to_i is an integer (the prices you see).

Resources