How to sort collection? - ruby-on-rails

How to sort collection on parametr n_text?
abc = [108, [#<Advert id: 7095, user_id: 5, n_text: "First text", created_at: "2019-06-03 00:49:00", images_count: 0>, #<Advert id: 7096, user_id: 7, n_text: "Second text", created_at: "2019-06-03 08:23:00", images_count: 1>,...]]
abc.order_by { |k, v| v[:n_text] } dont working.

abc.last.sort_by(&:n_text)
I think this will work, .last because you are going to sort last element of the abc array.

Related

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

Convert ActiveRecord::Relation into a usable array

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

Rails 4 Partial with Collection

I am doing something obviously wrong here, but I don't get it.
I have a partial call like so:
= render 'shared/purchase', collection: #purchases
#purchases is defined in the controller like so:
#purchases = current_user.purchases
But I get this error:
app/views/shared/_purchase.html.slim where line #3 raised:
undefined local variable or method `purchase' for #<<Class:0x007fd8ca54f970>:0x007fd8ca54eb60>
However, when I change the partial to just render the local_assigns I see this:
[:collection, #<ActiveRecord::Associations::CollectionProxy [#<Purchase id: 40, user_id: 20, purchaseable_id: 6, purchaseable_type: "PurchaseType", frequency: "Weekly", day: "Su", notes: "leave at gate", allergies: "peanuts", created_at: "2013-07-24 16:58:08", updated_at: "2013-07-24 16:58:08", size: "Normal", quantity: 2>, #<Purchase id: 41, user_id: 20, purchaseable_id: 5, purchaseable_type: "PurchaseType", frequency: "Weekly", day: "Su", notes: "leave at gate", allergies: "peanuts", created_at: "2013-07-24 16:58:08", updated_at: "2013-07-24 16:58:08", size: "Jumbo", quantity: 3>, #<Purchase id: 42, user_id: 20, purchaseable_id: 7, purchaseable_type: "PurchaseType", frequency: "Weekly", day: "Su", notes: "leave at gate", allergies: "peanuts", created_at: "2013-07-24 16:58:08", updated_at: "2013-07-24 16:58:08", size: nil, quantity: 1>, #<Purchase id: 43, user_id: 20, purchaseable_id: 8, purchaseable_type: "PurchaseType", frequency: "Weekly", day: "Su", notes: "leave at gate", allergies: "peanuts", created_at: "2013-07-24 16:58:08", updated_at: "2013-07-24 16:58:08", size: nil, quantity: 1>]>]
[:purchase, nil]
Why isn't each collection item getting picked up as the local variable purchase?
I'm tearing my hair out, I'm sure it's something stupid, I've done this many times before, and even compared old working code to this and I can't figure out what the problem is. Either it's a new Rails 4 thing that I'm not seeing in the docs, or I'm an idiot.
Thanks!
The Rails documentation on Layouts and Render in Rails gives an example using the partial parameter for render:
<h1>Products</h1>
<%= render partial: "product", collection: #products %>

Rails get record count from array

I use the following query to return a list of records
Rating.find(:all, :conditions => ["rating_set = ? and product_id = ?", 1, 2186417])
which returns:
[#<Rating id: 5, label: "Good", rating: 3.0, created_at: "2013-02-20 08:11:36", updated_at: "2013-02-20 08:11:36", recommendation_id: 2186417, notes: "exact match", rating_set: 1, product_id: 2186417>, #<Rating id: 6, label: "Good", rating: 3.0, created_at: "2013-02-20 08:11:36", updated_at: "2013-02-20 08:11:36", recommendation_id: 2054442, notes: "", rating_set: 1, product_id: 2186417>, #<Rating id: 7, label: "Fair", rating: 2.0, created_at: "2013-02-20 08:11:36", updated_at: "2013-02-20 08:11:36", recommendation_id: 2403501, notes: "", rating_set: 1, product_id: 2186417>, #<Rating id: 8, label: "Bad", rating: 3.0, created_at: "2013-02-20 08:11:36", updated_at: "2013-02-20 08:11:36", recommendation_id: 2344645, notes: "", rating_set: 1, product_id: 2186417>]
How can I get a count for each rating label. For example, how many records out of the total are "Good" or how many are "Bad" etc.
You can do that in at least 2 ways.
SQL
klass = Rating.where(rating_set: 1, product_id: 2186417])
good_count = klass.where(label: 'Good').count
bad_count = klass.where(label: 'Bad').count
Array
ratings = Rating.where(rating_set: 1, product_id: 2186417]).all
good_count = ratings.count { |r| r.label == 'Good' }
bad_count = ratings.count { |r| r.label == 'Bad' }
You could try a group by:
Rating.where(:rating_set => 1, :product_id => 2186417).group(:label).count.each{ |k,v| puts "#{k} #{v}" }
Resource: http://guides.rubyonrails.org/active_record_querying.html#group

Converting an array into string

I need to join output of a hash into a string.
The hash looks like this:
nas.location.walledgardens.to_s
=> "[#<Walledgarden id: 1, location_id: 12, url: \"polka.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">, #<Walledgarden id: 2, location_id: 12, url: \"test.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">, #<Walledgarden id: 3, location_id: 12, url: \"help.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">, #<Walledgarden id: 4, location_id: 12, url: \"yell.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">, #<Walledgarden id: 5, location_id: 12, url: \"sausage.com\", created_at: \"2012-05-14 17:02:47\", updated_at: \"2012-05-14 17:02:47\">]"
I need to join the url values into the following format:
polka.com,test.com,help.com
What the best way to do this? I can easily look through it but the output has line breaks and I need these removed plus the commas.
nas.location.walledgardens.collect { |w| w.url }.join(",")
The .collect method will collect all what that block returns and put it in an array, and then the join puts that array in a string, separated by whatever you give it (so a comma).
What you have is not a Hash, but an Array of Walledgarden objects (they look to be ActiveRecord::Base subclasses).
Try this:
nas.location.walledgardens.collect(&:url).join ","
(Note: #map and #collect are equivalent, so which one you choose should be a consideration of readability!)
Use Array#map:
nas.location.walledgardens.map(&:url).join ','

Resources