logo
down
shadow

Download a CSV file from FTP with Ruby on Rails and Update Existing Records


Download a CSV file from FTP with Ruby on Rails and Update Existing Records

By : polosandman
Date : November 21 2020, 03:00 PM
This might help you I am assuming that customer_order_id is unique.
You could try something like this -
code :
   def self.update_or_create(attributes)
     assign_or_new(attributes).save
   end


   Geek.where(customer_order_id: row.to_h["customer_order_id"]).update_or_create.( 
                                 customer_name: row.to_h["customer_name"],
                                 item_sku: row.to_h["item_sku"],
                                 quantity_to_ship: row.to_h["quantity_to_ship"],
                                 total_items_price: row.to_h["total_items_price"])
class Wheel < ApplicationRecord
require 'csv'

def self.update_or_create(attributes)
  obj = first || new
  obj.assign_attributes(attributes)
  obj.save!
end

def self.import(out)
    out ||= "#{Rails.root}/public/300-RRW Daily Inv Report.csv"
        CSV.foreach(out, :headers => true,
                  :converters => :all,
                  :header_converters => lambda { |h| h.downcase.gsub(' ', '_') }
                  ) do |row|
     Wheel.where(item: row.to_h["item"]).update_or_create(
                                     item_desc: row.to_h["item_desc"],
                                     total_quantity: row.to_h["total_quantity"])
  end
end


Share : facebook icon twitter icon
How to update existing records if conflict, Ruby on Rails

How to update existing records if conflict, Ruby on Rails


By : Maaz Aftab
Date : March 29 2020, 07:55 AM
Hope this helps Setting the uniqueness validation aside, this will re-index the positions:
code :
# build a new subcategory
subcategory = category.subcategories.build(:foo => :bar)

# some arbitrary, zero-based position desired by your user
position = 3

# insert the subcategory at the desired position
category.subcategories.insert(position, subcategory)

# use each with index to re-index all of your subcategories
category.subcategories.each_with_index do |sc, index|
   sc.position = index
end
Ruby/Rails updating existing records with duplicate's data

Ruby/Rails updating existing records with duplicate's data


By : user2761442
Date : March 29 2020, 07:55 AM
seems to work fine I have an app that has monitors the development of skills, it has many training_programs and each training_program has many participants. , you can use find_or_initialize_by and write something like this:
code :
excel_row =  { id: 33, name: "rob", id: 123456789, times_trained: 3, amount_spent: 65000 }
participant = Participant.find_or_initialize_by(id: excel_row[:id])
participant.name = excel_row[:name] #Set this row default 0 in your db
participant. amount_spent += excel_row[:name]) #Set this row default 0 in your db
participant.save
Can't update existing records in Rails app

Can't update existing records in Rails app


By : Hansong Wang
Date : March 29 2020, 07:55 AM
To fix this issue This is what I ended up doing, based off this (replacing the word user with event): https://www.railstutorial.org/book/updating_and_deleting_users#sec-unsuccessful_edits
events_controller.rb:
code :
def update
    @event = Event.find(params[:id])
    if @event.update_attributes(event_params)
      # Handle a successful update.
    else
      render 'update'
    end
  end
Ruby on rails add attribute to existing object from active records

Ruby on rails add attribute to existing object from active records


By : mollyhughes
Date : March 29 2020, 07:55 AM
wish helps you You're passing an Array of ActiveRecord objects, not hashes. The json converter will parse of the attributes of the model instead of custom variables assigned to those objects. Try converting the models to hashes:
code :
lesson = lesson.attributes
lesson['palindrome'] = 'TEST'
Ruby: Inserting records to existing rails database using non-rails script

Ruby: Inserting records to existing rails database using non-rails script


By : Phillip Hose
Date : March 29 2020, 07:55 AM
I wish this helpful for you Just to lead you in the right direction - you can use a Rake task for this. These are usually put in the lib/tasks directory.
It's a good idea to separate non-web related things such as seeding or updating a database. If this is a scheduled job, you can use whenever to hook the rake task to cron.
Related Posts Related Posts :
  • How to reduce duplication in Rails RSS reader sync.rake task?
  • Camaleon-CMS: How to disable media files edition
  • Rails 5.1 - JSON parameter is permitted but still prints as unpermitted in the log
  • In Ruby On Rails CLI, how can I list Helper Paths?
  • How to prevent nested create failing with scoped has_many in ActiveRecord?
  • Rails cant assign attributes for new entity
  • activeadmin has_many hide remove button
  • Ruby on Rails: How can I override a method from a gem while calling the super method
  • Dockerized Selenium with rails tests
  • View 3rd party api code
  • add a if condition to rails delete function and pass a alert message to view
  • i18n dont find the translation
  • Upgrading passenger to 5.1.11 breaks setup with 403
  • How to handle images in a Rails / Webpacker / React app?
  • Rails check_box_tag - save array into Postgres
  • custom query in active record with multiple joins
  • Testing Rails API controller POST with RSpec
  • Rails group_id to Insert statement
  • How to skip validation on update?
  • active model serializer has_many association not working
  • Time.use_zone is ignored during active record query
  • referencing foreign key attributes rails
  • Passing Post request through postman for has_many association in rails
  • Filter relationship in rails json api using many to many
  • link_to in data-content for a bootstrap 4 popover
  • rubyzip extracts empty file in activejob
  • Why is Rails running in development mode during rake test task?
  • Rspec testing model with null: false constraint
  • Specify UTC Offset instead of timezone to ActiveSupport::TimeWithZone
  • Carry Sass variables across all stylesheet files in Rails
  • Each loop outputs an unwanted dump of the records after the loop
  • Suddenly can't push to heroku: "unable to negotiate key exchange method"
  • Mapping ActiveRecord as dynamic key value pair on Rails
  • Rails form with checkboxes from enum (hash)
  • How to compare two items within Ruby on Rails?
  • Rails Routes - How to get nested IDs from URI Pattern
  • Optimize database query for time series data retrieving using postgresql and ruby on rails
  • How to store cryptocurrency balance without causing floating point errors in ruby/rails
  • unknown attribute in rails 5
  • undefined method `new' for #<Grease::Adapter(Less::Rails::ImportProcessor)
  • Get values without using sessions
  • Compatibility issue when using rails_admin_email gem
  • Passing values between objects rails
  • Should I check for updated attributes before making a db call?
  • Using minitest to test that hash contains array values of specific size
  • No implicit conversion of Array into String - Rails Migration
  • Headless Chrome with Rspec database connection not working
  • rails 5 User.find(params[:user_id]) nill
  • Rails scopes using many-to-many and joins
  • Link_to root_path not working in mail view
  • Status code 302 does not redirect after a POST call
  • validation errors are added only in production env
  • rails redirect user to profile page after destroy action
  • Incrementing a field with a Ruby on Rails call back
  • Rails+resque background job import not adding anything to the database
  • Rails Form Builder - How to place html attributes
  • Upgrading my app to Rails 5. Not sure what to make of errors on bundle install
  • Spree active menu
  • RSpec: Avoid using allow any instance of to receive
  • RSpec: Test a create action method in controller
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org