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' })
Related
I have a hash like so:
def my_requests
result = {
accepted: [],
rejected: [],
pending: [],
}
self.requests.each do |request|
serialized_request = RequestSerializer.new(request)
if request.accept == nil
result[:pending].push(serialized_request)
elsif request.accept
result[:accepted].push(serialized_request)
else
result[:rejected].push(serialized_request)
end
end
result
end
I will have a logged in user. I am trying to organize the logged in user's availabilities by id.
How do I sort each array by id. I know if this was just an array I can do:
array.sort_by{|request| request.id}
But how do I iterate through each key's array? I've tried multiple different ways and the only one that works is if I end up mapping over the hash and then another loop to sort the requests. But that doesn't return a hash. Is there a way for me to keep the structure and sort it?
The availabilities serializer is below:
class RequestSerializer < ActiveModel::Serializer
attributes :id, :start_time, :payment, :number_of_hours, :availability_id, :date, :name, :accept, :postcode, :phone_number
end
Below is one of the key, value pair outputs.
:rejected=>[#<RequestSerializer:0x00007fa416e168a8 #object=#<Request id: 64, payment: 200, number_of_hours: 20, accept: false, start_time: "2000-01-01 16:20:00", venue_id: 1, availability_id: 4, created_at: "2020-08-30 12:15:04", updated_at: "2020-08-30 12:15:52">, #instance_options={}, #root=nil, #scope=nil>, #<RequestSerializer:0x00007fa416e167b8 #object=#<Request id: 4, payment: 160, number_of_hours: 4, accept: false, start_time: "2000-01-01 16:15:00", venue_id: 2, availability_id: 5, created_at: "2020-06-17 21:19:07", updated_at: "2020-06-17 21:21:32">, #instance_options={}, #root=nil, #scope=nil>, #<RequestSerializer:0x00007fa416e166c8 #object=#<Request id: 71, payment: 100, number_of_hours: 1, accept: false, start_time: "2000-01-01 09:45:00", venue_id: 1, availability_id: 6, created_at: "2020-10-01 08:45:43", updated_at: "2020-10-01 08:46:04">, #instance_options={}, #root=nil, #scope=nil>, #<RequestSerializer:0x00007fa416e16560 #object=#<Request id: 66, payment: 30, number_of_hours: 3, accept: false, start_time: "2000-01-01 16:30:00", venue_id: 1, availability_id: 26, created_at: "2020-08-30 12:31:02", updated_at: "2020-08-30 12:32:10">, #instance_options={}, #root=nil, #scope=nil>, #<RequestSerializer:0x00007fa416e163f8 #object=#<Request id: 68, payment: 20, number_of_hours: 3, accept: false, start_time: "2000-01-01 12:00:00", venue_id: 1, availability_id: 28, created_at: "2020-09-01 08:17:26", updated_at: "2020-09-01 13:09:54">, #instance_options={}, #root=nil, #scope=nil>]
Thanks!
result.transform_values { |array| array.sort_by(&:request_id) }
If the arrays are not not arrays of requests, but RequestSerializer, just call .object on them to get the request to sort by.
result.transform_values do |array|
array.sort_by { |serializer| serializer.object.request_id }
end
Another option would be to define request_id on RequestSerializer
You have to sort each hash value separately:
result.each_value { |array| array.sort_by!(&:id) }
Hash#each_value traverses the values and sort_by! sorts the array in-place.
If you need to create a new sorted copy:
result.each_with_object({}) do |(key, value), list|
list[key] = value.sort_by(&:id)
end
As Stefan posted in the comments. I can use a database query to order the requests prior to splitting them into their arrays.
The answer that worked (without doing multiple loops) was:
def my_requests
result = {
accepted: [],
rejected: [],
pending: [],
}
requests.order(:id).each do |request|
serialized_request = RequestSerializer.new(request)
if request.accept == nil
result[:pending].push(serialized_request)
elsif request.accept
result[:accepted].push(serialized_request)
else
result[:rejected].push(serialized_request)
end
end
result
end
Simply by removing self. and using the .order query and the id attribute, everything comes out ordered!
Thanks Stefan! (and everyone else)
(Others worked with multiple methods or loops but as I was using Rails, the query is the quickest and easiest).
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
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 %>
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
I'm trying to add a new property to an object created through my User model.
a = User.find(7)
I get:
#<User id: 7, name: "Ewah", email: "stugnuz#yahoo.it", password_salt: "t4vPG0hgQVQMyIFeri6", persistence_token: "98f0cdfcb9462f3f74b1ae6ef48f0d72a015c6e04adda95fcd0...", login_count: 387, failed_login_count: 0, current_login_at: "2011-03-15 08:03:54", last_login_at: "2011-03-14 23:17:45", current_login_ip: "93.34.49.190", last_login_ip: "93.34.38.47", score: 2726, level: 7, created_at: "2010-10-13 22:33:21", updated_at: "2011-03-28 13:28:40", admin: true, avatar_file_name: "11.jpg", avatar_file_size: 78456, avatar_content_type: "image/jpeg", perishable_token: "PXTFtiMBxcoH3Iv7TmRh", score_this_week: 0, get_news: true, get_notices: true, bio: "Ho perso per strada Minnie anche in onore di Ken Sa...", invitation_id: nil, can_approve: false, no_score: false, facebook_uid: "1052260327", facebook_session_key: "", crypted_password: "05e5080268598607f5d1ece82db1b4d4c6ae12deeb880896ad2...", oauth2_token: "141832835841718|545eae41205d7a2ccb37d7c0-1052260327...", votes_count: 208, post_to_facebook: true, tutorial_step: 2, private: false, posts_count: 31, votes_remaining: 105, votes_this_week: 0, comments_count: 367, ignore: false>
I'd like to add the .votes_cast property to the "a" variable:
a.votes_cast = 5
But when I try to do this I get:
NoMethodError: undefined method `votes_casted=' for #<User:0x102c997f0>
What am I doing wrong?
Thanks,
Augusto
If this is to be a persistent property in your database then you should define a migration to add a column.
If it's just a temporary field in the User model then you can simply add an accessor to class User in app/models/user.rb.
class User < ActiveRecord::Base
attr_accessor :votes_cast
end