Ruby on rails save data inside loop - ruby-on-rails

object.each do |info|
#user_work_history.fb_user_id = facebook_session.user.id
#user_work_history.city = info.location.city
#user_work_history.country = info.location.state
#user_work_history.company_name = info.company_name
#user_work_history.description = info.description
#user_work_history.start_date = info.start_date
#user_work_history.end_date = info.end_date
#user_work_history.position = info.position
#user_work_history.updated_at = Time.now
#user_work_history.save
end
here is the code but inside loop data is not saving only one record is saved.

I believe you have to add
#user_work_history = UserWorkHistory.new
to the first line inside the loop. (or whatever the model is)

When you do that kind of loop you need to change the reference to the instance variable #user_work_history. What your loop does is that for each iteration it updates the state of the same object!
What you should do, is to set the #user_work_history before each iteration, like this:
object.each do |info|
#user_work_history = UserWorkHistory.new(:fb_user_id => facebook_session.user.id) # for example
#user_work_history.city = info.location.city
#user_work_history.country = info.location.state
(...)
#user_work_history.save # here it saves new tuple
end

Related

Adding values to a hash within/over multiple each loops

I have a concept called snapshot which basically stores a snapshot of how data looked at a certain period of time. What I'm building is a method that loops through the snapshots for each events, and builds a small hash outlining the ownership over time for a given shareholder.
def fetch_ownership_over_time(shareholder, captable)
#shareholder = Shareholder.find(shareholder.id)
#captable = Captable.find(captable.id)
#company = #captable.company.id
#ownership_over_time = []
#captable.events.collect(&:snapshot).each do |snapshot|
parsed_snapshot = JSON.parse(snapshot)
#ownership_over_time.push(parsed_snapshot["event"]["name"])
#ownership_over_time.push(parsed_snapshot["event"]["date"])
parsed_snapshot["shareholders"].each do |shareholder|
if shareholder["id"] == #shareholder.id
#ownership_over_time.push(shareholder["ownership_percentage"])
end
end
end
return #ownership_over_time
end
I then call this method in my view which successfully retrieves the correct values however they are not structured in any way:
["Event 1 ", "2018-11-19", "0.666666666666667", "Event 2 ", "2018-11-19", "0.333333333333333", "4th event ", "2018-11-19", "0.315789473684211"]
What I'd like to do now though is construct my hash so that each separate snapshot event contains a name, date and ownership_percentage.
Perhaps something like this:
ownership_over_time = [
{
event_name = "Event 1" #parsed_snapshot["event"]["name"]
event_date = "20180202" #parsed_snapshot["event"]["date"]
ownership_percentage = 0.37 #shareholder["ownership_percentage"]
},
{
event_name = "Event 2" #parsed_snapshot["event"]["name"]
event_date = "20180501" #parsed_snapshot["event"]["date"]
ownership_percentage = 0.60 #shareholder["ownership_percentage"]
}
]
My challenge though is that the ["event"]["name"] an ["event"]["date"] attributes I need to fetch when looping over my snapshots i.e. the first loop (.each do |snapshot|) whereas I get my ownership_percentage when looping over shareholders - the second loop (.each do |shareholder|).
So my question is - how can I build this hash in "two" places so I can return the hash with the 3 attributes?
Appreciative of guidance/help - thank you!
You have to create a new hash for the object and append that hash to the array of objects you are creating.
def fetch_ownership_over_time(shareholder, captable)
#shareholder = Shareholder.find(shareholder.id)
#captable = Captable.find(captable.id)
#company = #captable.company.id
#ownership_over_time = []
#captable.events.collect(&:snapshot).each do |snapshot|
parsed_snapshot = JSON.parse(snapshot)
shareholder = parsed_snapshot['shareholders'].select { |s| s['id'] == #shareholder.id }.first
local_snapshot = {
'event_name' => parsed_snapshot['event']['name'],
'event_date' => parsed_snapshot['event']['date'],
'ownership_percentage' => shareholder.try(:[], "ownership_percentage") || 0
}
#ownership_over_time.push local_snapshot
end
return #ownership_over_time
end
Notice that I changed your second loop to a select. As you currently have it, you risk on pushing two percentages if the id is found twice.
EDIT:
Added functionality to use a default value if no shareholder is found.

Array of hashes is overriding data directly to array

I want to make an array of hashes. But the problem is after first iteration when code goes to next line then it directly replaces the content of array.
#item_name =[]
item = {}
#invoiceinfo.each do |invoice|
item[:name] = Invoiceinfo.find(#invoiceinfo.id).item.name
item[:desc] = Invoiceinfo.find(#invoiceinfo.id).desc
item[:unit_price] = Invoiceinfo.find(#invoiceinfo.id).unit_price
byebug
#item_name.push (item)
end
This is what i am getting
after first iteration suppose i have this data
#item_name = [{:name=>"usman", :desc=>"sample ", :unit_price=>100}]
As soon as next line is executed it directly changes #item_name(name variable)
After executing item[:name] = Invoiceinfo.find(#invoiceinfo.id).item.name
the content of the #item_name is changed
#item_name = [{:name=>"next_name", :desc=>"sample ", :unit_price=>100}]
Any help would be appreciated.
Thannks
Try something like this
#item_name = []
#invoiceinfo.each do |invoice|
invoice_info = Invoiceinfo.find(#invoiceinfo.id)
item = {}
item[:name] = invoice_info.item.name
item[:desc] = invoice_info.desc
item[:unit_price] = invoice_info.unit_price
#item_name.push(item)
end
If you consider using ruby paradigms and best practices in ruby code, this mistake won’t happen in the future.
#item_name = #invoiceinfo.each_with_object([]) do |invoice, acc|
invoice_info = Invoiceinfo.find(#invoiceinfo.id)
acc.push(
name: invoice_info.item.name,
desc: invoice_info.desc
unit_price: invoice_info.unit_price
)
end

How to "shift" objects from ActiveRecord array

I have this method
def gen_events(score)
events = location.events
(1..rand(5..7)).each do |n|
random = rand(0.139..1).round(3)
rarity = Character.get_rarity(random)
event = events.where(rarity: rarity).shuffle.shift #<-- HERE
self.events << event
end
end
Currently, the shift method only grabs the first element, but doesn't remove it, how can I go about making it so that it does both?
This is not an array: events.where(rarity: rarity), this is an ActiveRecord scope, you can't remove things from it without destroying and erasing them from database. Instead, you should keep an array of object you already found, and use it to filter future results:
def gen_events(score)
events = location.events
new_events = []
(1..rand(5..7)).each do |n|
random = rand(0.139..1).round(3)
rarity = Character.get_rarity(random)
event = events.where(rarity: rarity).where.not(id: new_events.map(&:id).sample
new_events << event
end
self.events << new_events
end

Creating a record from a third-party object with same field names?

I have a Charge model in my database with field names that match up to the fields returned from a third-party API.
charge = ThirdPartyChargeAPI.find(1)
Charge.create do |e|
e.object = charge.object
e.paid = charge.paid
e.amount = charge.amount
e.currency = charge.currency
e.refunded = charge.refunded
e.amount_refunded = charge.amount_refunded
e.failure_message = charge.failure_message
e.failure_code = charge.failure_code
e.description = charge.description
e.metadata = charge.metadata
e.captured = charge.captured
e.balance_transaction = charge.balance_transaction
e.customer = charge.customer
e.invoice = charge.invoice
e.created = charge.created
end
Seems painfully redundant, though. Is there some way to merge this without having to basically set every single field manually?
Assuming there's no way to get a direct hash from the API (I would imagine there would be, since it's probably coming in as XML or JSON), you could try a direct map of instance variables:
Charge.create do |c|
charge.instance_variables.each do |var|
value = charge.instance_variable_get(var)
c.instance_variable_set(var, value)
end
end
This is making some pretty bold assumptions about the structure of the charge you're getting back from the API though - any instance variable in it that you don't want will be included.

Push a hash into an array in a loop rails

I am trying to add hashes to an array whilst iterating through an each loop. Here's my controller code: the line I'm struggling with is setting the #royaltiesbychannel variable in the each loop:
def royalty(isbn)
sales_hash_by_channel = Sale.find_all_by_isbn_id(#isbn).group_by(&:channel_id)
sales_hash_by_channel.each do |ch_id, sale_array|
#royaltiesbychannel = Array.new()
value_total_by_channel = sale_array.sum(&:value)
quantity_total_by_channel = sale_array.sum(&:quantity)
#isbn.rules.each do |rule|
next unless rule.channel_id == ch_id
case quantity_total_by_channel
when 0..5000
#royaltiesbychannel = #royaltiesbychannel << {ch_id => value_total_by_channel * 0.5}
# (some other case-when statements)
end
end
end
In the console, when I set the ch_id and the value to something new and push the new values into the array:
#royaltiesbychannel = #royaltiesbychannel << {ch_id => value_total_by_channel * 0.5}
I get a nice array of hashes:
[{1=>100000.0}, {2=>3000.0}]
However, when I do #royaltiesbychannel.inspect in the view, I get just one key-value pair:
[{2=>3000.0}]
For ref:
#royaltiesbychannel.class = Array
#royaltiesbychannel.class = 1
#sales_hash_by_channel.class = Hash
#sales_hash_by_channel.size = 2
#isbn.rules.size = 4
So it looks like the push into the array is overwriting rather than adding. What am I doing wrong? Have I completely missed the point on how loops and .push work? Many thanks in advance.
You are initializing the array within the loop:
#royaltiesbychannel = Array.new()
It is being re-initialized each time, therefore you get only one result. Move it outside the each loop.
Your #royaltiesbychannel initialization is inside the first loop, so every time it starts that loop again it empties the array. Move it outside the loop and you should get the result you want.
def royalty(isbn)
#royaltiesbychannel = Array.new()
sales_hash_by_channel = Sale.find_all_by_isbn_id(#isbn).group_by(&:channel_id)
sales_hash_by_channel.each do |ch_id, sale_array|
value_total_by_channel = sale_array.sum(&:value)
quantity_total_by_channel = sale_array.sum(&:quantity)
#isbn.rules.each do |rule|
next unless rule.channel_id == ch_id
case quantity_total_by_channel
when 0..5000
#royaltiesbychannel = #royaltiesbychannel << {ch_id => value_total_by_channel * 0.5}
# (some other case-when statements)
end
end
end
You're setting #royaltiesbychannel to a new Array object during each iteration over sales_hash_by_channel should you be instead initialising it once outside of that loop instead?

Resources