Thursday, June 23, 2016

Rails order / sort dates based on two different dates | Fixed issues

Rails order / sort dates based on two different dates | Fixed issues


Rails order / sort dates based on two different dates

Posted: 23 Jun 2016 07:53 AM PDT

Each record contains two fields - field1 and field2. Both contain dates.

For reach record: 1 field might have been filled in, for another it might be 2 of the fields or none at all.

I'd like to in the most efficient way possible order them based on this.

So it would compare field1 and field2 for a record and find which one has the latest date. It would then list all of the records in order based on this and then display the records that don't have any kind of entry.

I had it sorted for just field1 like this:

order("CASE WHEN field1 IS NULL THEN 1 ELSE 0 END, field1 desc"  

But when I try and introduce field 2 into the query it doesn't give me the results that I would expect.

Any ideas?

Installing bundler gives me "you don't have write permissions" error

Posted: 23 Jun 2016 07:31 AM PDT

I had used ruby version manager (rvm) to install a new version of ruby. Running the command rvm rubiesshows all the version of rubies that are installed. The list is given below.

rvm rubies       ruby-1.9.3-p551 [ x86_64 ]     ruby-2.1.5 [ x86_64 ]     ruby-2.2.4 [ x86_64 ]   * ruby-2.3.0 [ x86_64 ]     ruby-2.3.1 [ x86_64 ]    # => - current  # =* - current && default  #  * - default  

I tried to run the command bundle exec rake rb:mgirate and I get the following error.

/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/dependency.rb:319:in `to_specs': Could not find 'bundler' (>= 0.a) among 5 total gem(s) (Gem::LoadError)  Checked in 'GEM_PATH=:/nix/.nix-profile/lib/ruby/gems', execute `gem env` for more information  

The error states that bundler isn't installed. I ran the command gem install bundle and I get the following error.

ERROR:  While executing gem ... (Gem::FilePermissionError)      You don't have write permissions for the /nix/.nix-profile/lib/ruby/gems directory.  

It says that I don't have write permissions. I googled the error and it has something to do with updating ruby and ruby version. The reason why I updated to a new ruby version was because heroku run rake db:seed wasn't seeding data in production. I though it might be due to compatibility issues. Therefore, I decided to update to the new version of ruby. The servers, postgresql and everything else works fine. I can't run bundle because I can't install the gem. Any hep would be greatly appreciated. Thanks!

Rails redirect_to loses the https protocol and goes to http

Posted: 23 Jun 2016 07:27 AM PDT

When using redirect_to example_path in the controller the protocol gets changed to http. I want the protocol to remain the same as the original request e.g. if I'm using https I want to be redirected to https://example_path... and if I'm using http I want to be redirected to http://example_path...

I know I can use config.force_ssl = true but I want ssl to be optional.

undefined method `edit_user_password_url'

Posted: 23 Jun 2016 07:21 AM PDT

I am trying to do forgot password using clearance but getting this error ???

undefined method `edit_user_password_url' for #<#<Class:0x00000003898f98>:0x00000003757d50>  


At this line

<%= link_to t(".link_text", default: "Change my password"),      edit_user_password_url(@user, token: @user.confirmation_token.html_safe) %>  </p>    <p><%= raw t(".closing") %></p>  


<p><%= raw t(".closing") %></p>  


Here is my password controller code

class PasswordsController < ApplicationController        layout 'login'      skip_before_filter :require_login, only: [:create, :edit, :new, :update], raise: false      skip_before_filter :authorize, only: [:create, :edit, :new, :update], raise: false      before_filter :ensure_existing_user, only: [:edit, :update]        skip_before_action :authenticate_user, :except => [:destroy]          def new      end        def create          if user = find_user_for_create              user.forgot_password!              deliver_email(user)              flash[:notice] = t('password.send_email')              redirect_to  sign_in_path          else              flash[:notice] = t('password.invalid_email')              render 'new'          end        end        def edit          @user = User.find(params[:user_id])      end        def update          @user = find_user_for_update          if @user.update_password password_reset_params              #Activity.add_activity(@user,'forgot_password','')              sign_in @user              redirect_to sign_in_path          else            end      end      private      def deliver_email(user)          mail = ::ClearanceMailer.change_password(user)          if Gem::Version.new(Rails::VERSION::STRING) >= Gem::Version.new("4.2.0")              mail.deliver_later          else              mail.deliver          end      end        def password_reset_params          if params.has_key? :user              ActiveSupport::Deprecation.warn %{Since locales functionality was added, accessing params[:user] is no longer supported.}              params[:user][:password]          else              params[:password_reset][:password]          end      end        def find_user_by_id_and_confirmation_token          user_param = Clearance.configuration.user_id_parameter          Clearance.configuration.user_model.          find_by_id_and_confirmation_token params[user_param], params[:token].to_s      end        def find_user_for_create          Clearance.configuration.user_model.          find_by_normalized_email params[:password][:email]      end          def find_user_for_update          find_user_by_id_and_confirmation_token      end        def ensure_existing_user          unless find_user_by_id_and_confirmation_token              flash_failure_when_forbidden              render template: "passwords/new"          end      end        def flash_failure_when_forbidden          flash.now[:notice] = translate(:forbidden,          scope: [:clearance, :controllers, :passwords],          default: t('flashes.failure_when_forbidden'))      end        def flash_failure_after_update          flash.now[:notice] = translate(:blank_password,          scope: [:clearance, :controllers, :passwords],          default: t('flashes.failure_after_update'))      end      end  

Rake searchkick reindex not working in heroku search box

Posted: 23 Jun 2016 07:02 AM PDT

I unable reindex in heroku once i deploy my code to heroku server with running heroku run rake searchkick:reindex CLASS=Listing, i did do heroku run rake db:migrate

rake aborted!  Faraday::TimeoutError: Net::ReadTimeout  /app/vendor/bundle/ruby/2.2.0/gems/faraday-0.9.2/lib/faraday/adapter/net_http.rb:82:in `perform_request'  /app/vendor/bundle/ruby/2.2.0/gems/faraday-0.9.2/lib/faraday/adapter/net_http.rb:40:in `block in call'  /app/vendor/bundle/ruby/2.2.0/gems/faraday-0.9.2/lib/faraday/adapter/net_http.rb:87:in `with_net_http_connection'  /app/vendor/bundle/ruby/2.2.0/gems/faraday-0.9.2/lib/faraday/adapter/net_http.rb:32:in `call'  /app/vendor/bundle/ruby/2.2.0/gems/searchkick-1.3.0/lib/searchkick/middleware.rb:9:in `call'  /app/vendor/bundle/ruby/2.2.0/gems/faraday-0.9.2/lib/faraday/rack_builder.rb:139:in `build_response'  /app/vendor/bundle/ruby/2.2.0/gems/faraday-0.9.2/lib/faraday/connection.rb:377:in `run_request'  /app/vendor/bundle/ruby/2.2.0/gems/elasticsearch-transport-1.0.17/lib/elasticsearch/transport/transport/http/faraday.rb:21:in `block in perform_request'  

Rails: Sqlite3 to PostgreSQL heroku deployment Undefined Table ERROR

Posted: 23 Jun 2016 06:57 AM PDT

I've built a rails app and on pushing it up to heroku and running heroku run rake db:migrate i receive the error:

Migrating to CreateFollowingRelationships (20160615113231)     (0.4ms)  BEGIN  == 20160615113231 CreateFollowingRelationships: migrating =====================  -- create_table(:following_relationships)     (7.1ms)  CREATE TABLE "following_relationships" ("id" serial primary key, "follower_id" integer, "followed_user_id" integer, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_39102b381e"  FOREIGN KEY ("follower_id")    REFERENCES "followers" ("id")  , CONSTRAINT "fk_rails_048c8f7cd9"  FOREIGN KEY ("followed_user_id")    REFERENCES "followed_users" ("id")  )     (0.5ms)  ROLLBACK     (0.5ms)  SELECT pg_advisory_unlock(2837140123622957145)  rails aborted!  StandardError: An error has occurred, this and all later migrations canceled:    PG::UndefinedTable: ERROR:  relation "followers" does not exist  : CREATE TABLE "following_relationships" ("id" serial primary key, "follower_id" integer, "followed_user_id" integer, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_39102b381e"  FOREIGN KEY ("follower_id")    REFERENCES "followers" ("id")  , CONSTRAINT "fk_rails_048c8f7cd9"  FOREIGN KEY ("followed_user_id")    REFERENCES "followed_users" ("id")  )  

The relationship I have setup is for users to follow users and be followed. It works perfectly in development. This is the first time i've had this error and can't find a solution. Please see the rest of my code below.

db/schema.rb

ActiveRecord::Schema.define(version: 20160618122126) do      create_table "chats", force: :cascade do |t|      t.integer  "user_id"      t.string   "title"      t.text     "description"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.integer  "profile_id"      t.index ["profile_id"], name: "index_chats_on_profile_id"      t.index ["user_id"], name: "index_chats_on_user_id"    end      create_table "comments", force: :cascade do |t|      t.integer  "profile_id"      t.integer  "chat_id"      t.text     "body"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.index ["chat_id"], name: "index_comments_on_chat_id"      t.index ["profile_id"], name: "index_comments_on_profile_id"    end      create_table "following_relationships", force: :cascade do |t|      t.integer  "follower_id"      t.integer  "followed_user_id"      t.datetime "created_at",       null: false      t.datetime "updated_at",       null: false      t.index ["followed_user_id"], name: "index_following_relationships_on_followed_user_id"      t.index ["follower_id"], name: "index_following_relationships_on_follower_id"    end      create_table "locations", force: :cascade do |t|      t.string   "locationable_type"      t.integer  "locationable_id"      t.string   "suburb"      t.integer  "user_id"      t.datetime "created_at",        null: false      t.datetime "updated_at",        null: false      t.string   "address"      t.string   "state"      t.string   "country"      t.string   "postcode"      t.float    "latitude"      t.float    "longitude"      t.index ["locationable_type", "locationable_id"], name: "index_locations_on_locationable_type_and_locationable_id"      t.index ["user_id"], name: "index_locations_on_user_id"    end      create_table "orders", force: :cascade do |t|      t.integer  "buyer_id"      t.integer  "seller_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "posts", force: :cascade do |t|      t.integer  "profile_id"      t.integer  "user_id"      t.string   "title"      t.text     "body"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.index ["profile_id"], name: "index_posts_on_profile_id"      t.index ["user_id"], name: "index_posts_on_user_id"    end      create_table "profiles", force: :cascade do |t|      t.integer  "user_id"      t.text     "bio"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.index ["user_id"], name: "index_profiles_on_user_id"    end      create_table "tutoring_relationships", force: :cascade do |t|      t.integer  "tutor_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.integer  "tutee_id"      t.index ["tutee_id"], name: "index_tutoring_relationships_on_tutee_id"      t.index ["tutor_id"], name: "index_tutoring_relationships_on_tutor_id"    end      create_table "users", force: :cascade do |t|      t.string   "email",                           null: false      t.string   "password_digest",                 null: false      t.datetime "created_at",                      null: false      t.datetime "updated_at",                      null: false      t.string   "username"      t.boolean  "tutor",           default: false      t.index ["email"], name: "index_users_on_email", unique: true      t.index ["username"], name: "index_users_on_username", unique: true    end      create_table "votes", force: :cascade do |t|      t.string   "votable_type"      t.integer  "votable_id"      t.string   "voter_type"      t.integer  "voter_id"      t.boolean  "vote_flag"      t.string   "vote_scope"      t.integer  "vote_weight"      t.datetime "created_at"      t.datetime "updated_at"      t.index ["votable_id", "votable_type", "vote_scope"], name: "index_votes_on_votable_id_and_votable_type_and_vote_scope"      t.index ["voter_id", "voter_type", "vote_scope"], name: "index_votes_on_voter_id_and_voter_type_and_vote_scope"    end    end  

models/following_relationship.rb

class FollowingRelationship < ApplicationRecord    belongs_to :follower, class_name: 'User'    belongs_to :followed_user, class_name: 'User'  end  

models/user.rb

class User < ActiveRecord::Base    has_one :profile, dependent: :destroy    has_many :chats    validates :email, presence: true, uniqueness: true    validates :password_digest, presence: true      has_many :follower_relationships,      foreign_key: :followed_user_id,      class_name: 'FollowingRelationship'    has_many :followers, through: :follower_relationships      has_many :followed_user_relationships,      foreign_key: :follower_id,      class_name: "FollowingRelationship"    has_many :followed_users, through: :followed_user_relationships          has_many :tutee_relationships,      foreign_key: :tutor_id,      class_name: 'TutoringRelationship'    has_many :tutees, through: :tutee_relationships      has_many :tutor_relationships,      foreign_key: :tutee_id,      class_name: 'TutoringRelationship'    has_many :tutors, through: :tutor_relationships      def following? user      followed_user_ids.include?(user.id)    end      def is_connected? user      tutee_ids.include?(user.id)    end  end  

Please excuse the messy model, it would usually be in a helper method but for this post it's here. If anyone has any ideas please let me know! Thanks

elasticsearch faceted navigation

Posted: 23 Jun 2016 07:19 AM PDT

I'm trying to create a rails app like the one here on elasticsearch aggregations. I updated it to work with the current elasticsearch 2.3. The javascript works well but the filter returns nothing when I select more that one checkbox. The code different from the app here which does not handle checkboxs. What am I missing?

filter looks like this:

  __set_filters = lambda do |key, f|      @search_definition[:post_filter][:and] ||= []      @search_definition[:post_filter][:and]  |= [f]        @search_definition[:aggregations][key.to_sym][:filter][:bool][:must] ||= []      @search_definition[:aggregations][key.to_sym][:filter][:bool][:must]  |= [f]    end    if options[:category]    f = { term: { "categories,name" => options[:category] } }    __set_filters.(:location, f)  end    if options[:location]    f = { term: { "location,name" => options[:location] } }    __set_filters.(:categories, f)  end  

How to optimize queries and remove SQL Injection

Posted: 23 Jun 2016 06:58 AM PDT

I have following query

query = {}  if params[:post_id]      query.merge!('post_id' => "profiles.post_id = '#{params[:post_id]}'")  end  if params[:name].present?    query.merge!('name' => "name = '#{params[:name]}'")  end  if params[:gender].present?    query.merge!('gender' => "gender = '#{params[:gender}' ")  end    ProductPost.includes(:profiles).where("#{query.values.join(' and ') }").references(:profiles)  

How to optimize above code and how to remove my SQL Injection. I'm getting SQL Injection on every value of my HASH.

Thanks.

Running Delayed::Job on different port in rails

Posted: 23 Jun 2016 07:05 AM PDT

I'm running rails application on different ports 3001 and 3002. For bulk operations i'm using

    gem 'delayed_job_active_record', '4.1.1'  

When the workers start

rake jobs:work

I want that when the rake jobs run, the operations should hit 3002 port to avoid the load on port 3001 which is exposed to public url. How can i configure to share the load of all background jobs to run on rails server with port 3002.

Rails: ActionController::UrlGenerationError, No route matches, missing required keys

Posted: 23 Jun 2016 07:13 AM PDT

The following error is displayed when I try to create new data.

ActionController::UrlGenerationError (No route matches {:room_id=>nil, :action=>"index", :controller=>"events"} missing required keys: [:room_id]):  

models

models/rooms.rb          has_many :events, inverse_of: :room, dependent: :destroy        has_many :amounts, inverse_of: :room, dependent: :destroy        accepts_nested_attributes_for :events, allow_destroy: true    models/events.rb          has_one :amount, inverse_of: :schedule, dependent: :destroy        accepts_nested_attributes_for :amount, allow_destroy: true  

routes.rb

...    resources :events,              only: [:new, :create, :edit, :update]      resources :rooms do      resources :events    end    ...  

When I click link_to for new_room_event_path(1), the above error is displayed. It generates root/rooms/1/events/new.

view

    <% if logged_in? %>        <% if current_user?(@user) %>          <% if schedule.rooms.blank? %>            <%= link_to "Add event", new_room_event_path(1), class: "btn btn-sn btn-primary" %>            <br>          <% end %>        <% end %>      <% end %>  

The reason why I designate new_room_event_path(1) is that this is first time to create data.

events_controller.rb

  before_action :load_room      def new        @event = Event.new      @event.room = @room      @event.build_amount      @event.amount.schedule = @room.schedule      @event.amount.room = @room      end      private        def load_room        if Room.exists?(id: params[:room_id])          @room = Room.find(params[:room_id])        else          @room = Room.new        end      end  

It could be appreciated if you could give me any suggestion.

rspec factory girl pass association to association

Posted: 23 Jun 2016 06:26 AM PDT

Given these Rails models:

class Human    has_many :pets    has_many :vet_visits  end  class Pet    belongs_to :human     has_many :vet_visits  end  class VetVisit    belongs_to :human    belongs_to :pet  end  

I need an rspec factory to make a VetVisit. But:

FactoryGirl.define do    factory :vet_visit, class: 'VetVisit' do       association :human, factory: :human      association :pet, factory: :pet    end    factory :pet, class: 'Pet' do       association :human, factory: :human    end    factory :human, class: 'Human' do       after(:create) do | human |        create :pet, human: human      end    end  end  

results in a vet_visit with a human and a pet which are not each other's respective pet/human.

How do I make a factory which creates a vet_visit which has a pet with a human which is the same human as referenced by the vet_visit?

To clear any doubt, I am not in fact making a vetinary system, this is an abstract example from a more complex system, removing the human and doing vet_visit.pet.human in the code is not suitable

Rails - migrate from hstore to jsonb

Posted: 23 Jun 2016 06:42 AM PDT

I use Postgresql. I tried the following migration to cast a field from hstore to jsonb in Rails.

change_column :table_name, :field_name, 'jsonb USING CAST(field_name AS jsonb)'  

I get the following exception:

PG::DatatypeMismatch: ERROR: default for column "field_name" cannot be cast automatically to type jsonb.

Why do not change DB, How to resave the rollbacked object

Posted: 23 Jun 2016 05:49 AM PDT

This code is unusual.
I am programming a Long Running Transactions(with Web API).
So, I need tricky program.
I want to resave the rollbacked object(piyo2).

piyo2 = nil  ActiveRecord::Base.transaction do    piyo1 = Piyo.find_by(id: 1)    piyo1.name = 'hoge'    piyo1.save!    piyo2 = Piyo.find_by(id: 2)    piyo2.name = 'foo'    piyo2.save!    raise ActiveRecord::Rollback  end  piyo2.save! # log show BEGIN COMMIT. But Not show execute SQL.  piyo2.name # keep foo. But DB no change.  

My Solution.

piyo2 = nil  ActiveRecord::Base.transaction do    piyo1 = Piyo.find_by(id: 1)    piyo1.name = 'hoge'    piyo1.save!    piyo2 = Piyo.find_by(id: 2)    piyo2.name = 'foo'    piyo2.save!    raise ActiveRecord::Rollback  end  piyo2_retry = Piyo.find_by(id: piyo2.id) # one more find_by  piyo2_retry.update!(name: piyo2.name)  

This is the best solution?
Why piyo2.save! # log show BEGIN COMMIT. But No execute SQL. this code not wok?

ruby array of hashes merge on key

Posted: 23 Jun 2016 05:51 AM PDT

I have an array of hashes like so:

[{"id"=>1, "score"=>4, "capability_id"=>1, "membership_id"=>1,     "location_id"=>1, "organisation_id"=>1},   {"id"=>16, "score"=>5, "capability_id"=>1, "membership_id"=>2,     "location_id"=>2, "organisation_id"=>1},   {"id"=>31, "score"=>3, "capability_id"=>1, "membership_id"=>3,    "location_id"=>1, "organisation_id"=>2},   {"id"=>46, "score"=>3, "capability_id"=>1, "membership_id"=>4,    "location_id"=>3, "organisation_id"=>2},   {"id"=>61, "score"=>1, "capability_id"=>1, "membership_id"=>5,    "location_id"=>1, "organisation_id"=>3},   {"id"=>76, "score"=>6, "capability_id"=>1, "membership_id"=>6,    "location_id"=>2, "organisation_id"=>3},   {"id"=>91, "score"=>2, "capability_id"=>1, "membership_id"=>7,    "location_id"=>3, "organisation_id"=>3}]  

Which I want to turn into this:

[{"id"=>1, "score"=>{1=>3, 2=>4}, "capability_id"=>1, "membership_id"=>1, "location_id"=>1, "organisation_id"=>1...

Where score is an object with location_id => score for that location_id

Any suggestions?

run elasticsearch on digitalocean

Posted: 23 Jun 2016 06:41 AM PDT

I'm trying to move my application from heroku to digital ocean.

One main part of my application is elastic search. It works locally by me typing in elastic search and it running on localhost:9200 This works lovely.

IT works fine on heroku. I use searchly for heroku

However i'm now moving to digital ocean. I'm running dokku on digital ocean trying to make it work, So far i've got the website on and up and running. (Yay!!)

However i'm struggling to get the search engine working. I was looking at the plugin and got really confused so any help would be great!

Thanks Sam

Not able to export data to an excel sheet

Posted: 23 Jun 2016 07:10 AM PDT

I am using to_xls and spreadsheet gem to export data to excel sheet in rails4

However, I am not able to export the data to excel sheet even if the excel sheet fires open.

I am following this tutorial

http://code.dblock.org/2011/09/01/exporting-data-to-excel-in-ruby-on-rails-w-spreadsheet-and-toxls.html

orders_controller.rb

def index    @orders = Order.all.includes(:status,:document,:platform, payment:               [:status]).where(status_id: Orders::Status.where(name:               ['INPROGRESS', 'COMPLETED']).pluck(:id)).paginate(:page =>               params[:page], :per_page => 30).order('id Desc')      @order_statuses = Orders::Status.all      @delivery_statuses = Orders::DeliveryStatus.all                          respond_to do |format|                           format.html                         format.xls do                         send_data(                                     Order.where(status_id:                                             Orders::Status.where(name:                                     ['COMPLETED',                                   'INPROGRESS' ]).pluck(:id))                                   .includes(:status, :platform,                                            :payment).map{                                            |order|                                            {                                       id: order.id, txnid: order.txnid,                                     created_at: order.created_at,                                     product: order.product,                                     payment:                                                                order.payment.status.name,                                     status: order.status.name,                                       total_amount: order.total_amount,                                         discount: order.discount,                                     platform: order.platform.name                                     }}.to_xls,                         content_type: 'application/vnd.ms-excel',                         filename: 'orders.xls' )                      end                    end                  end  

orders/index.html.erb

<table id='myOrdersTable'class="table table-bordered">  <thead>  <tr>    <th>Trans ID</th>    <th>Date(dd/mm/yy)</th>    <th>Product</th>    <th>Payment</th>    <th>Status</th>    <th>Total amount</th>    <th>Discount</th>    <th>Platform</th>    <th>Draft</th>     <th>Edit Draft</th>    <th>Upload Soft Copy</th>    <th colspan="3"></th>  </tr>  </thead>    <tbody>  <% @orders.each do |order| %>    <tr>      <td><%= order.txnid %></td>      <td><%= order.created_at.strftime('%d-%b-%Y') %></td>      <td><%= order.product %></td>      <td><%= order.payment.status.name if order.payment %></td>      <td><%= order.status.name %></td>      <td><%= order.total_amount %></td>      <td><%= order.discount %></td>      <td><%= order.platform.name %></td>      <td          :          :          :      <% end %>    </tbody>    </table>    <%= will_paginate @orders %>          :          :   <%#= link_to 'New Order', new_order_path %>   <%= link_to 'Exporting', "/admin/orders.xls", :class =>'btn btn-primary'     %>  

Here in the link if call

 <%= link_to 'Exporting', orders_path(request.parameters.merge({:format    => :xls})), :class =>'btn btn-primary' %>  

it gives a template missing error(Dont know why) .Hence I am not using the above link in the code to get the export button. This helps me generate an excel sheet, but not able to export all the columns from the index.html.erb page and their values into the sheet. Just gives a blank spreadsheet. How can I export all these data in to sheet? Please help !I am a beginner so kindly elaborate and let me know if more data is needed.

Bulk insert of parent/children at the same time

Posted: 23 Jun 2016 06:44 AM PDT

I am trying to do a bulk insert of a pair of parent/child models to MySQL DB tables, but it seems there is no way I could do it with the standard ActiveRecord feature. So, I tried activerecord-import gem, but it does not support recursive insert for MySQL either...

# Book has_many authors / Author belongs to Book  books = []  10000.times do |i|     book = Book.new(:name => "book #{i}")    book.author.build(:name => "author #{i}")    books << book  end  Book.import books, recursive: true # THIS DOES NOT WORK  

I also tried to achieve it with raw SQL, but I was not unable to find a way to keep the reference of each parent/child because at the time I want to insert the child data, its parent have not had its id yet.
Dose anyone know how I could solve this problem?

Cleaning a hrefs within an array

Posted: 23 Jun 2016 06:24 AM PDT

I'm storing a series of a hrefs in an array and I want to clean them so that either just the link is left or so that the apostrophes are taken out. Can anybody help me clean the array in this manner?

The below is one extract from the array to provide an example of what is being stored

<a href="http://www.abdn.ac.uk/study/courses/undergraduate/B9C7/">View course details on provider's website</a>  

Could this possibly be done using gsub, if so, how?

Edited to include: I've created the array as follows, by scraping data:

def process_course_details(course_details)      details_array =[]      details_link = true       entry_link = true                details_info = {}              # Sets all data in hash              details_info[:url]          = course_details.search('div.coursedetails_programmeurl a')                details_array.push(details_info)              print_details_info(details_info)               entry_link = course_details.search('ul.details_tabs a').first           if entry_link               @details_entry = process_entry(@mechanize.get(entry_link["href"]))               @details_entry = clean_link(@details_entry)               details_info[:entry] = @details_entry             end      end  

Rails Sidekiq Queue size not working

Posted: 23 Jun 2016 05:36 AM PDT

I have a Rails app with 2 jobs (ImportCsvJob and ProcessCsvJob). So that I can visibly hint in the app that there are still jobs in the queue I have this helper method (inside application_helper.rb):

module ApplicationHelper     def queued_job_count          Sidekiq::Queue.new.size      end  end  

Then I use it on my index controller which is then passed to the view for processing and giving the visual hint in the app.

  def index      @still_have_jobs = !queued_job_count.zero?    end  

However, this works when I still had 1 background Job (ImportCsvJob), but when I added the (ProcessCsvJob) it does not work anymore.

import_csv_job.rb

require 'open-uri'    class ImportCsvJob < ActiveJob::Base    queue_as :default      def perform(csv_record)      csv_record[:object_changes] = ApplicationController.helpers.generate_hash(csv_record[:object_changes])      ObjectRecord.create(csv_record)    end  end  

process_csv_job.rb

class ProcessCsvJob < ActiveJob::Base    queue_as :default      def perform(csv_path)      csv_file = open(csv_path,'rb:UTF-8')        options = {          row_sep: :auto, col_sep: ",",           user_provided_headers: [:object_id, :object_type, :timestamp, :object_changes],           remove_empty_values: true,           headers_in_file: true      }        SmarterCSV.process(csv_file, options) do |array|          ImportCsvJob.perform_later(array.first)      end    end    end  

and lastly, in the model where this is called:

ProcessCsvJob.perform_later(gdrive.uploaded_file_link)  

When I try to debug in Rails console using Sidekiq::Queue.new.size, it still gives out 0.

Running:

redis-server  bundle exec sidekiq  

Why should I use post_via_redirect?

Posted: 23 Jun 2016 05:36 AM PDT

In Rails' guide for Integration test there's an example with post_via_redirect. But why would one use "via_redirect" instead of plainly post?

require 'test_helper'    class UserFlowsTest < ActionDispatch::IntegrationTest    test "login and browse site" do      # login via https      https!      get "/login"      assert_response :success        post_via_redirect "/login", username: users(:david).username, password: users(:david).password      assert_equal '/welcome', path      assert_equal 'Welcome david!', flash[:notice]        https!(false)      get "/articles/all"      assert_response :success      assert assigns(:articles)    end  end  

incompatible character encodings

Posted: 23 Jun 2016 05:26 AM PDT

I am getting this issue "ActionView::Template::Error (incompatible character encodings: UTF-8 and ASCII-8BIT)", from client browser, so i am bit confused, where this is happening actually, one place is

    <%= form_for(resource, :as => resource_name, :url =>       session_path(resource_name), html: { class: "signup" }) do |f| %>  

but before this line, i am seeing one line is like this

 Started GET "/checkstatus/status?utf8=�??&status_id=12686"   Parameters: {"utf8"=>"\xE2??", "status_id"=>"12686"}  

is there any issues with clients browser? in these two statements, what will be the most change to occur this?

Inline C output value store on rails controller

Posted: 23 Jun 2016 05:02 AM PDT

I am using inline C to get some output. What I am trying to do is execute the inline C code and render its output to rails view via controller. The code snippet for inline C is:

class Something    inline(:C) do |builder|      builder.c 'int test1() {       char array[20] = "-------Hello from Ruby!------\n";       printf("%s", array);       return array;       }'     end  end  

Object is created in the controller of the rails application this way.

def index      something = Something.new      @something = something.test1  end  

Now, when I try to store output value of the inline C, it just is not applicable while the output is displayed on the rails log(not on the log file). I am sure that the value displayed is via return array; of the Something class. The index method has @something instance set which just stores some value like 4421355280 , but not the value. ie "-------Hello from Ruby!------" I have an index to render the corresponding controller action.

<h1>Travel</h1>  <h3><%= @something %></h3>  

How can I possibly store output value "-------Hello from Ruby!------" into @something? Output of inline C

Thanks in advance.

Issue in rendering the header/footer in ubuntu 14.04

Posted: 23 Jun 2016 05:02 AM PDT

I am using the below version gems to render my PDF

wicked_pdf - 0.11.0  wkhtmltopdf - 0.1.2  wkhtmltopdf-binary - 0.9.9.3.  

Below is my controller cod

render :pdf => "#{@route.route_name} report",   :template => 'reports/index.pdf.erb',  page_size: "A4",  :header => {:html => { :template=> 'reports/footer.html.erb'}  }  

I am trying to render the header in the PDF pages. It works absolutely fine in Ubuntu 12.04, but not in 14.04.

Please help me out in this.

Could not find gem mysql2 even though it's in the Gemfile and bundle install is in the Dockerfile

Posted: 23 Jun 2016 07:53 AM PDT

I'm trying to create and run a Rails app in container (Ruby image). I create the app scaffolding using: docker-compose.exe run -d web rails new . --force --database=mysql --skip-bundle and I'm trying to run with: docker-compose.exe up -d.

Here is my docker-compose.yml and rails.dockerfile:

version: '2'    services:    web:      build:         context: .        dockerfile: .docker/rails.dockerfile      command: rails server -p 3000 -b '0.0.0.0'      volumes:         - .:/var/www      ports:         - "3000:3000"      depends_on:        - 'mysql'      networks:        - ddoc-network        mysql:      image: mysql      environment:         MYSQL_ROOT_PASSWORD: 'SOMETHING'      networks:        - ddoc-network      networks:    ddoc-network:      driver: bridge  

rails.dockerfile

FROM ruby:2.3.1    MAINTAINER Juliano Nunes    RUN apt-get update -qq && apt-get install -y build-essential mysql-client libmysqlclient-dev nodejs  RUN mkdir /var/www  WORKDIR /var/www    ADD Gemfile /var/www/Gemfile  ADD Gemfile.lock /var/www/Gemfile.lock  RUN bundle install  ADD . /var/www    CMD ['rails', 'server', '-b', '0.0.0.0']  

However, when I run docker-compose up -d and check the logs, I get this:

[36mweb_1    |[0m /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/resolver.rb:356:in `block in verify_gemfile_dependencies_are_found!': Could not find gem 'mysql2 (< 0.5, >= 0.3.13)' in any of the gem sources listed in your Gemfile or available on this machine. (Bundler::GemNotFound)  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/resolver.rb:331:in `each'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/resolver.rb:331:in `verify_gemfile_dependencies_are_found!'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/resolver.rb:200:in `start'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/resolver.rb:184:in `resolve'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/definition.rb:200:in `resolve'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/definition.rb:140:in `specs'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/definition.rb:185:in `specs_for'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/definition.rb:174:in `requested_specs'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/environment.rb:19:in `requested_specs'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/runtime.rb:14:in `setup'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler.rb:95:in `setup'  [36mweb_1    |[0m     from /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.4/lib/bundler/setup.rb:19:in `<top (required)>'  [36mweb_1    |[0m     from /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:133:in `require'  [36mweb_1    |[0m     from /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:133:in `rescue in require'  [36mweb_1    |[0m     from /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require'  [36mweb_1    |[0m     from /usr/local/bundle/bin/rails:15:in `<main>'  

Why?

how to continue after the nested model forms railscasts?

Posted: 23 Jun 2016 05:09 AM PDT

I followed the railscasts nested model form part 1, making some changes to have it work in rails 4. Basically, I created 3 models: Quiz, Question, and Answer, and they all belong_to the model intuitively above them. A form in the new action is used to create the quiz itself.

However, I'm at a bit of loss on how to proceed now. After creating the quiz, the show view looks like this: enter image description here

done by iterating through @quiz.questions and @quiz.questions.answers and just displaying them on the page with their respective content attributes.

That's great for displaying just the questions and answers, but it doesn't accept user input at all. How do I make it so the user can use radio buttons to select an answer, and have it submit SOMEWHERE to save the results for grading and future reference for the user?

I've actually tried to create a form simply within the show action and have it save to another model but I got stuck extremely quickly. I'm finding it really difficult to both display the results AND accept user input for the displayed results. I also can't figure out a good way to save this data. Making another 3 models with the equivalent of Questions having something like a user_answer attribute seems difficult to implement and messy. I'm a beginner of the grandest caliber so any help would be great!

Cleaning scraped <a href> rails

Posted: 23 Jun 2016 06:21 AM PDT

I have scraped data from a website and entered it into an array using the code below:

  def process_course_details(course_details)          details_array =[]          details_link = true           entry_link = true                    details_info = {}                  # Sets all data in hash                  details_info[:url] = clean_link(course_details.search('div.coursedetails_programmeurl a'))                  details_array.push(details_info)                  print_details_info(details_info)                   entry_link = course_details.search('ul.details_tabs').first         end  

The code above stores the element being pulled as such:

<a href="http://www.abdn.ac.uk/study/courses/undergraduate/C8R1/">View course details on provider's website</a>  

But I'd like to clean the above to the below:

http://www.abdn.ac.uk/study/courses/undergraduate/C8R1/  

or failing that remove the apostrophe and have this:

<a href="http://www.abdn.ac.uk/study/courses/undergraduate/C8R1/">View course details on providers website</a>`  

How can I have the java ciper algorithm and ruby cipher algorithm in sync?

Posted: 23 Jun 2016 05:10 AM PDT

I have this code in my rails app:

require 'openssl'  require 'digest/sha1'  require 'base64'    KEY="secret_key"  data  = "secret message"     def encrypt_value(data)      cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")      cipher.encrypt      cipher.key = Digest::SHA256.digest(KEY)      encrypted = cipher.update(data)+cipher.final      return encrypted   end    def decrypt_value1(data)      cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")      cipher.decrypt      cipher.key = Digest::SHA256.digest(KEY)      decrypted = cipher.update(data)+cipher.final      data = Base64.decode64(decrypted)      return data  end  

And java code:

import java.security.AlgorithmParameters;   import java.security.NoSuchAlgorithmException;   import java.security.SecureRandom;     import javax.crypto.BadPaddingException;   import javax.crypto.Cipher;   import javax.crypto.IllegalBlockSizeException;   import javax.crypto.SecretKey;   import javax.crypto.SecretKeyFactory;   import javax.crypto.spec.IvParameterSpec;   import javax.crypto.spec.PBEKeySpec;   import javax.crypto.spec.SecretKeySpec;   import javax.xml.bind.DatatypeConverter;     public class EncryptionDecryption {         private static String salt;       private static int iterations = 65536  ;       private static int keySize = 256;       private static byte[] ivBytes;        // private static SecretKey secretKey;       private static final byte[] secretKey = "secret_key".getBytes();         public static void main(String []args) throws Exception {             salt = getSalt();             char[] message = "secret message".toCharArray();           System.out.println("Message: " + String.valueOf(message));           System.out.println("Encrypted: " + encrypt(message));           System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));       }         public static String encrypt(char[] plaintext) throws Exception {           byte[] saltBytes = salt.getBytes();             SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");           PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);           //secretKey = skf.generateSecret(spec);           SecretKeySpec secretSpec = new SecretKeySpec(secretKey, "AES");             Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");           cipher.init(Cipher.ENCRYPT_MODE, secretSpec);           AlgorithmParameters params = cipher.getParameters();           ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();           byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));             return DatatypeConverter.printBase64Binary(encryptedTextBytes);       }         public static String decrypt(char[] encryptedText) throws Exception {             System.out.println(encryptedText);             byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));           SecretKeySpec secretSpec = new SecretKeySpec(secretKey, "AES");             Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");           cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));             byte[] decryptedTextBytes = null;             try {               decryptedTextBytes = cipher.doFinal(encryptedTextBytes);           }   catch (IllegalBlockSizeException e) {               e.printStackTrace();           }   catch (BadPaddingException e) {               e.printStackTrace();           }             return new String(decryptedTextBytes);         }         public static String getSalt() throws Exception {             SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");           byte[] salt = new byte[20];           sr.nextBytes(salt);           return new String(salt);       }   }  

How can I have both of them work with each other, for example if I send an encrypted data to java app from rails app it should be able to decode it and vice-versa.

Carrierwave + Heroku

Posted: 23 Jun 2016 05:16 AM PDT

Any idea how to use Carrierwave to upload images with Heroku.

I added this to the uploader file:

def cache_dir    "#{Rails.root}/tmp/uploads"  end  

but images still don't save! After uploading an image, it saves and once you refresh the page, the image breaks.

Any help would be appreciated! Thanks

undefined method `prepend' for Searchkick::Query:Class

Posted: 23 Jun 2016 07:26 AM PDT

After adding gem searchkick to my Gemfile I get this error when I try to delpoy the project:

/home/deploy/apps/razborki/shared/bundle/jruby/1.9/gems/faraday-0.8.9/lib/faraday/request/multipart.rb:4 warning: already initialized constant DEFAULT_BOUNDARY  DEBUG[eff60d47]     rake aborted!  DEBUG[eff60d47]     NoMethodError: undefined method `prepend' for Searchkick::Query:Class  DEBUG[eff60d47]     /home/deploy/apps/razborki/shared/bundle/jruby/1.9/gems/searchkick-1.3.0/lib/searchkick/logging.rb:179:in `(root)'  DEBUG[eff60d47]     /home/deploy/apps/razborki/shared/bundle/jruby/1.9/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'  DEBUG[eff60d47]     /home/deploy/apps/razborki/shared/bundle/jruby/1.9/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:232:in `load_dependency'  DEBUG[eff60d47]     /home/deploy/apps/razborki/shared/bundle/jruby/1.9/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'  DEBUG[eff60d47]     /home/deploy/apps/razborki/shared/bundle/jruby/1.9/gems/searchkick-1.3.0/lib/searchkick.rb:1:in `(root)'  DEBUG[eff60d47]     /home/deploy/apps/razborki/shared/bundle/jruby/1.9/gems/searchkick-1.3.0/lib/searchkick.rb:12:in `(root)'  DEBUG[eff60d47]     /home/deploy/apps/razborki/releases/20160622173816/config/application.rb:9:in `(root)'  DEBUG[eff60d47]     /home/deploy/apps/razborki/releases/20160622173816/Rakefile:1:in `(root)'  DEBUG[eff60d47]     /home/deploy/apps/razborki/releases/20160622173816/Rakefile:5:in `(root)'  DEBUG[eff60d47]     (See full trace by running task with --trace)  

How can I fix it?

This is my Gemfile.lock :

GIT    remote: git://github.com/capistrano/sshkit.git    revision: 9027b0dcd0b25a762d90ab154ca44fca9fb57e00    specs:      sshkit (1.5.1)        colorize        net-scp (>= 1.1.2)        net-ssh (>= 2.8.0)    GIT    remote: git://github.com/elasticsearch/elasticsearch-rails.git    revision: 2f2c0fb7a25ece68fd3a9eec7b9026848e66fa4f    specs:      elasticsearch-model (0.1.6)        activesupport (> 3)        elasticsearch (> 0.4)        hashie      elasticsearch-rails (0.1.6)    GIT    remote: git://github.com/rweng/jquery-datatables-rails.git    revision: db17aa0145164095b2b21f83f1ef7ccf91b9ea54    specs:      jquery-datatables-rails (3.1.1)        actionpack (>= 3.1)        jquery-rails        railties (>= 3.1)        sass-rails    GEM    remote: http://rubygems.org/    specs:      aasm (4.0.0)      actionmailer (4.1.8)        actionpack (= 4.1.8)        actionview (= 4.1.8)        mail (~> 2.5, >= 2.5.4)      actionpack (4.1.8)        actionview (= 4.1.8)        activesupport (= 4.1.8)        rack (~> 1.5.2)        rack-test (~> 0.6.2)      actionview (4.1.8)        activesupport (= 4.1.8)        builder (~> 3.1)        erubis (~> 2.7.0)      activemodel (4.1.8)        activesupport (= 4.1.8)        builder (~> 3.1)      activerecord (4.1.8)        activemodel (= 4.1.8)        activesupport (= 4.1.8)        arel (~> 5.0.0)      activerecord-jdbc-adapter (1.3.11)        activerecord (>= 2.2)      activesupport (4.1.8)        i18n (~> 0.6, >= 0.6.9)        json (~> 1.7, >= 1.7.7)        minitest (~> 5.1)        thread_safe (~> 0.1)        tzinfo (~> 1.1)      addressable (2.3.6)      ansi (1.4.3)      arel (5.0.1.20140414130214)      ast (2.3.0)      authlogic (3.4.0)        activerecord (>= 3.2)        activesupport (>= 3.2)        request_store (~> 1.0.5)      autoprefixer-rails (3.1.2.20141016)        execjs      bootstrap_form (2.3.0)      buftok (0.2.0)      builder (3.2.2)      capistrano (3.2.1)        i18n        rake (>= 10.0.0)        sshkit (~> 1.3)      capistrano-bundler (1.1.3)        capistrano (~> 3.1)        sshkit (~> 1.2)      capistrano-rails (1.1.2)        capistrano (~> 3.1)        capistrano-bundler (~> 1.1)      capistrano-rbenv (2.0.2)        capistrano (~> 3.1)        sshkit (~> 1.3)      capistrano3-puma (0.8.2)        capistrano (~> 3.0)        puma (>= 2.6)      carrierwave (0.10.0)        activemodel (>= 3.2.0)        activesupport (>= 3.2.0)        json (>= 1.7)        mime-types (>= 1.16)      chronic (0.10.2)      coderay (1.1.1)      coffee-rails (4.0.1)        coffee-script (>= 2.2.0)        railties (>= 4.0.0, < 5.0)      coffee-script (2.2.0)        coffee-script-source        execjs      coffee-script-source (1.7.0)      colorize (0.7.3)      concurrent-ruby (1.0.0)      concurrent-ruby (1.0.0-java)      connection_pool (2.2.0)      dalli (2.7.1)      database_cleaner (1.4.1)      descendants_tracker (0.0.4)        thread_safe (~> 0.3, >= 0.3.1)      diff-lcs (1.2.5)      elasticsearch (1.0.8)        elasticsearch-api (= 1.0.7)        elasticsearch-transport (= 1.0.7)      elasticsearch-api (1.0.7)        multi_json      elasticsearch-transport (1.0.7)        faraday        multi_json      equalizer (0.0.9)      erubis (2.7.0)      exception_notification (4.0.1)        actionmailer (>= 3.0.4)        activesupport (>= 3.0.4)      execjs (2.0.2)      factory_girl (4.5.0)        activesupport (>= 3.0.0)      factory_girl_rails (4.5.0)        factory_girl (~> 4.5.0)        railties (>= 3.0.0)      faraday (0.8.9)        multipart-post (~> 1.2.0)      ffi (1.9.3)      ffi (1.9.3-java)      ffi-compiler (0.1.3)        ffi (>= 1.0.0)        rake      figaro (1.1.0)        thor (~> 0.14)      font-awesome-rails (4.2.0.0)        railties (>= 3.2, < 5.0)      geocoder (1.2.1)      gibberish (1.4.0)      gmaps4rails (2.1.2)      haml (4.0.6)        tilt      haml-rails (0.9.0)        actionpack (>= 4.0.1)        activesupport (>= 4.0.1)        haml (>= 4.0.6, < 5.0)        html2haml (>= 1.0.1)        railties (>= 4.0.1)      hashie (3.4.0)      hike (1.2.3)      hirb (0.7.1)      html2haml (2.0.0)        erubis (~> 2.7.0)        haml (~> 4.0.0)        nokogiri (~> 1.6.0)        ruby_parser (~> 3.5)      http (0.5.0)        http_parser.rb      http_parser.rb (0.6.0)      http_parser.rb (0.6.0-java)      i18n (0.7.0)      jdbc-mysql (5.1.33)      jquery-fileupload-rails (0.4.1)        actionpack (>= 3.1)        railties (>= 3.1)      jquery-rails (3.1.2)        railties (>= 3.0, < 5.0)        thor (>= 0.14, < 2.0)      jquery-ui-rails (4.2.0)        railties (>= 3.2.16)      jquery_mobile_rails (1.4.5)        railties (>= 3.1.0)      jruby-memcache-client (1.7.2)      json (1.8.3)      json (1.8.3-java)      kaminari (0.16.2)        actionpack (>= 3.0.0)        activesupport (>= 3.0.0)      launchy (2.4.2)        addressable (~> 2.3)      launchy (2.4.2-java)        addressable (~> 2.3)        spoon (~> 0.0.1)      letter_opener (1.2.0)        launchy (~> 2.2)      libv8 (3.16.14.7)      mail (2.6.3)        mime-types (>= 1.16, < 3)      memoizable (0.4.2)        thread_safe (~> 0.3, >= 0.3.1)      method_source (0.8.2)      mime-types (2.4.3)      mini_portile (0.6.2)      minitest (5.6.0)      multi_json (1.10.1)      multipart-post (1.2.0)      mysql2 (0.3.17)      net-scp (1.2.1)        net-ssh (>= 2.6.5)      net-ssh (2.9.1)      nokogiri (1.6.6.2)        mini_portile (~> 0.6.0)      nokogiri (1.6.6.2-java)      parser (2.3.1.2)        ast (~> 2.2)      powerpack (0.1.1)      protected_attributes (1.0.7)        activemodel (>= 4.0.1, < 5.0)      pry (0.10.3)        coderay (~> 1.1.0)        method_source (~> 0.8.1)        slop (~> 3.4)      pry (0.10.3-java)        coderay (~> 1.1.0)        method_source (~> 0.8.1)        slop (~> 3.4)        spoon (~> 0.0)      pry-rails (0.3.4)        pry (>= 0.9.10)      puma (2.12.2)      puma (2.12.2-java)      quiet_assets (1.1.0)        railties (>= 3.1, < 5.0)      rack (1.5.5)      rack-protection (1.5.3)        rack      rack-test (0.6.3)        rack (>= 1.0)      rails (4.1.8)        actionmailer (= 4.1.8)        actionpack (= 4.1.8)        actionview (= 4.1.8)        activemodel (= 4.1.8)        activerecord (= 4.1.8)        activesupport (= 4.1.8)        bundler (>= 1.3.0, < 2.0)        railties (= 4.1.8)        sprockets-rails (~> 2.0)      rails-i18n (4.0.3)        i18n (~> 0.6)        railties (~> 4.0)      rails-observers (0.1.2)        activemodel (~> 4.0)      railties (4.1.8)        actionpack (= 4.1.8)        activesupport (= 4.1.8)        rake (>= 0.8.7)        thor (>= 0.18.1, < 2.0)      rainbow (2.1.0)      rake (10.4.2)      redis (3.2.2)      redis-namespace (1.5.1)        redis (~> 3.0, >= 3.0.4)      ref (1.0.5)      remotipart (1.2.1)      request_store (1.0.5)      rmagick (2.13.4)      rmagick4j (0.3.8)      rspec-core (3.2.3)        rspec-support (~> 3.2.0)      rspec-expectations (3.2.1)        diff-lcs (>= 1.2.0, < 2.0)        rspec-support (~> 3.2.0)      rspec-mocks (3.2.1)        diff-lcs (>= 1.2.0, < 2.0)        rspec-support (~> 3.2.0)      rspec-rails (3.2.1)        actionpack (>= 3.0, < 4.3)        activesupport (>= 3.0, < 4.3)        railties (>= 3.0, < 4.3)        rspec-core (~> 3.2.0)        rspec-expectations (~> 3.2.0)        rspec-mocks (~> 3.2.0)        rspec-support (~> 3.2.0)      rspec-support (3.2.2)      rubocop (0.40.0)        parser (>= 2.3.1.0, < 3.0)        powerpack (~> 0.1)        rainbow (>= 1.99.1, < 3.0)        ruby-progressbar (~> 1.7)        unicode-display_width (~> 1.0, >= 1.0.1)      ruby-progressbar (1.8.1)      ruby_parser (3.7.0)        sexp_processor (~> 4.1)      sass (3.2.19)      sass-rails (4.0.3)        railties (>= 4.0.0, < 5.0)        sass (~> 3.2.0)        sprockets (~> 2.8, <= 2.11.0)        sprockets-rails (~> 2.0)      scrypt (1.2.1)        ffi-compiler (>= 0.0.2)        rake      searchkick (1.3.0)        activemodel        elasticsearch (>= 1)        hashie      sexp_processor (4.6.0)      sidekiq (4.1.0)        concurrent-ruby (~> 1.0)        connection_pool (~> 2.2, >= 2.2.0)        redis (~> 3.2, >= 3.2.1)      simple_oauth (0.2.0)      sinatra (1.4.6)        rack (~> 1.4)        rack-protection (~> 1.4)        tilt (>= 1.3, < 3)      sitemap_generator (5.0.5)        builder      slop (3.6.0)      smarter_csv (1.0.19)      spoon (0.0.4)        ffi      sprockets (2.11.0)        hike (~> 1.2)        multi_json (~> 1.0)        rack (~> 1.0)        tilt (~> 1.1, != 1.3.0)      sprockets-rails (2.2.1)        actionpack (>= 3.0)        activesupport (>= 3.0)        sprockets (>= 2.8, < 4.0)      therubyracer (0.12.1)        libv8 (~> 3.16.14.0)        ref      therubyrhino (2.0.4)        therubyrhino_jar (>= 1.7.3)      therubyrhino_jar (1.7.4)      thor (0.19.1)      thread_safe (0.3.5)      thread_safe (0.3.5-java)      tilt (1.4.1)      tinymce-rails (4.0.19)        railties (>= 3.1.1)      turn (0.8.3)        ansi      twitter (5.5.1)        addressable (~> 2.3)        buftok (~> 0.2.0)        descendants_tracker (~> 0.0.3)        equalizer (~> 0.0.9)        faraday (>= 0.8, < 0.10)        http (~> 0.5.0)        http_parser.rb (~> 0.6.0)        json (~> 1.8)        memoizable (~> 0.4.0)        simple_oauth (~> 0.2.0)      tzinfo (1.2.2)        thread_safe (~> 0.1)      uglifier (2.5.0)        execjs (>= 0.3.0)        json (>= 1.8.0)      unicode-display_width (1.0.5)      whenever (0.9.4)        chronic (>= 0.6.3)    PLATFORMS    java    ruby    DEPENDENCIES    aasm    activerecord-jdbc-adapter    authlogic    autoprefixer-rails    bootstrap_form    capistrano (~> 3.2.0)    capistrano-bundler    capistrano-rails    capistrano-rbenv    capistrano3-puma    carrierwave (~> 0.10.0)    coffee-rails (~> 4.0.0)    dalli (~> 2.7.1)    database_cleaner    elasticsearch-model!    elasticsearch-rails!    exception_notification    factory_girl_rails    figaro    font-awesome-rails    geocoder    gibberish    gmaps4rails (= 2.1.2)    haml-rails (~> 0.9)    hirb    jdbc-mysql    jquery-datatables-rails!    jquery-fileupload-rails    jquery-rails    jquery-ui-rails    jquery_mobile_rails    jruby-memcache-client    kaminari (~> 0.16.2)    letter_opener    mysql2 (~> 0.3.15)    protected_attributes    pry-rails    puma    quiet_assets    rails (~> 4.1)    rails-i18n (~> 4.0.0)    rails-observers    rake (>= 10.0.0)    redis-namespace    remotipart (~> 1.2)    rmagick    rmagick4j    rspec-rails    rubocop    sass-rails (~> 4.0.2)    scrypt    searchkick    sidekiq    sinatra    sitemap_generator    smarter_csv    sshkit (~> 1.3)!    therubyracer    therubyrhino    tinymce-rails (~> 4.0.0)    turn (~> 0.8.3)    twitter    uglifier (>= 2.5.0)    whenever    BUNDLED WITH     1.12.5  

searchkick 1.3.0

ruby-2.1.0

rails-4.1.8

Errno::ENOENT: No such file or directory FTP Rails

Posted: 23 Jun 2016 04:29 AM PDT

In ftp.rb:

Net::FTP.open('something.com', '****', '****') do |ftp|      ftp.passive = true      ftp.binary = true      ftp.list('*.xml').each do |file|        puts "#{ftp.pwd} is the current directory." #/ is the current directory        file_name="#{file.split.last}"        if File.exist?(file_name)         xml_file_obj = File.new(file_name)       else        puts "#{ftp.pwd} is the current directory." #/ is the current directory.        xml_file_obj = File.new(file_name)      end      ftp.putbinaryfile(xml_file_obj, "/Completed_files/#{file_name}")    end    end  

In remote server i have two XML files and a folder Completed_files.Here i am coping these files to Completed_files folder.

First file get copied successfully but getting error like Errno::ENOENT: No such file or directory @ rb_sysopen - file2.xml when copying second file to the folder.Help me out.

No comments:

Post a Comment