lundi 30 avril 2018

How to reflect the changes of a dynamically changing variable in a controller function to views?

During form submission, i am uploading a file to s3. In the uploading function i am trying to track upload progress. My controller sample code is bellow.

file = File.open('/path/to/file', 'r')
count = 0
obj = s3.buckets['my-bucket'].objects['object-key']
obj.write(:content_length => file.size) do |buffer, bytes|
  buffer.write(file.read(bytes))
  count = count +1
end
file.close

The only remaining task is, How can I reflect the changes happening to the count variable in views in real time.

jeudi 26 avril 2018

undefined method `name' for nil:NilClass block in skill_list

undefined method `name' for nil: NilClass block in skill_list Why is there the block in skill list? Do I need to call skiil_list some way?

def skill_list
    array = skill_associations.map do |sa|
     sa.skill.name
    end
   array.join(", ")
end

def skill_list=(names)
    self.skill_associations.delete_all
    self.skills = names.split(",").map do |m|
      Skill.where(name: m.strip).first_or_create!
    end
end

mardi 24 avril 2018

Rails 4 - Ensure all has_many associations exists while using includes during eager loading

I have a Rails4 app which has many models and many has_many.Now when i am eager loading using Model.includes(:other_models), i want the query to execute only when all the includes are persisted or present, but i am unable to do so.

for example -

in my shop.rb

has_one :announcement, :dependent => :destroy
has_many :pictures, -> { where.not('venue_id' => nil) }, class_name: 'Picture', :dependent => :destroy
has_many :ratings, -> { where(rateable_type: 'Shop') } , foreign_key: 'rateable_id' ,:class_name=>"Rate"
has_many :videos, :dependent => :destroy
has_many :testimonials, :dependent => :destroy
has_many :managers, :dependent => :destroy
has_many :pricing_details, :dependent => :destroy
has_many :comments, :as=> :commentable, :class_name => 'Comment',:dependent => :destroy
has_many :user_inquiries, :dependent => :destroy
has_many :venue_checkers, :as=> :contactable, :class_name => 'VenueChecker',:dependent => :destroy

So now, if i want to load a Shop, which should also have all the dependencies persisted, i try this ...

Shop.includes(:contact_detail,address,pictures,videos,annoucement, :hall_request,:hall_facilities ,:event_categories....other models).find(1010)..

i get the Shop, if i remove the address or contact_detail or any other model, it still shows up, which i dont want.

i want a method that should only return the shop when it has all its has_many dependencies persisted else return nothing.

i want something like this..

    def get_completed_shops_only
       Shope.distinct.includes(:hall_request,:hall_facilities ,:event_categories, :address,:contact_detail,:pictures,:videos,:ratings....other models)
    end
### Shop.get_completed_shops_only.find(100) - must return a shop with all dependencies present else nothing.

I know includes puts a Left join, which matches all for left table and right table if it exists, but how can i do it here.I can do the same with joins but that will hit performance.I just want to includes persisted items only.

Kindly help

It is not coded (sha 256- > scrypt)

My current open-source is mining based on sha 256. I want to change this to scrypt, but the output value before and after the change does not change.

I need your help badly.

enter image description here

enter image description here

how to change the sender email credentials according to the user of application in rails

I want to give different sender email credentials according to the user of application in rails which will be fetched from database.

lundi 23 avril 2018

pghero - Getting error while launching postgres through ec2 instance

I created a new ec2 instance and installed docker and tried connecting pgHero to my postgreSQL instance. I have connectivity to postgres through my ec2 instance but i am getting the following error when i access pgHero.

could not translate host name <DB URL> to address: Name or service not known

enter image description here

However, using the same docker image I am able to connect to pghero on my local. Thanks in advance!

input must be a string or IO - JSON serialize error rails

I have a model object User which has a JSON(mysql 5.7 JSON column too) column in it. My model object looks like this

class User < ActiveRecord::Base 

    after_initialize :set_defaults
    serialize :group_condition, JSON

    def set_defaults
      self.group_condition ||= []
    end

end

When I create a new object using User.new, when set_defaults is called, I am getting this error. input must be a string or IO During the initialization of User object group_condition is null and it will be added with user given input later on. But, Coz of input must be a string or IO error I am not able to proceed. Any Help will be much appreciated

Empty CSV file from rails

I am new to ruby on rails and I am having trouble in exporting the data to csv. I have followed the following video:

https://medium.com/coderaga/rails-import-export-csv-data-without-gem-fbf2a36a84f6

I have put require 'csv' in application.rb file also.

My student.rb model has:

def self.to_csv(fields = column_names, options = {})
    CSV.generate(options) do |csv|
      csv << fields
      all.each do |student|
        csv << student.attributes.values_at(*fields)
      end
    end
end

My students_controller has following:

    def index
    @students=Student.all
    puts @students
    respond_to do |format|
      format.html
      format.csv{send_data @students.to_csv(['UIN', 'Name' ,'Section', 'Attempts', 'Score'])}
    end
  end

I think the all.each statement is empty as when I am doing puts student.attributes.values_at(*fields), there is nothing so that is why there is nothing being written. But I am not sure how can I fix it.

Student Load (0.3ms)  SELECT "students".* FROM "students"
#<Student:0x007f9a2386ddb8>
#<Student:0x007f9a2386dc78>
#<Student:0x007f9a2386db38>
  CACHE Student Load (0.0ms)  SELECT "students".* FROM "students"

Please help

samedi 21 avril 2018

developing a CRUD web api with login, log out and registration functionality on ruby on rails

  1. The user should able to Register, login and logout from the site. N.B - Don’t use any third party Gem for register/login/logout

  2. The site should have a lot of products of different categories. Display all products and user should be able to filter products by category.

  3. Filter popular products by category. Popular products will be determined by unique hit counts by the different number of users, i.e, if product1 hit count, is 100 by 2 different users and product2 hit count is 95 by 5 different users, in this case, product2 will be in the top of the list of popular products.

N.B: Use minimal number of third-party gems

vendredi 20 avril 2018

How to decrepit cookie into rails application if you know the secrete

I need to decrept cookie into my rails application which is set by express node application running into same domain. I know the secrete key which is used by node/express pplication to write those cookies.

validate regexp mongoid "_id"

I would like validate in my rails User model mongoid "_id" field with a regexp.

This is a field with 24 characters, something like this:

#<User _id: 5ad98cf7a8abbc7110f5783c

Thank you

jeudi 19 avril 2018

Rails skip validation within model with save?

I have Rails code like :

1 def charge_card
2            return charge_on_house if house_account?
3            assign_order_number
4           if credit_card?
5              begin
6                save!   #==>here
7                charge = Stripe::Charge.create(
8                  amount: (total.to_f * 100).ceil,
9                  currency: 'usd',
10                  customer: customer.stripe_id,
11                  card: payment_method,
12                 description:"Saint Germain Order: #{self.number}"
13                  )
14                self.update(
15                  payment_status: 'paid'
16                  )
17                self.finish!
18              rescue Stripe::StripeError => e
19                self.update(
20                  admin_comments: e.message,
21                  )
22                self.decline!
23              ensure
24                notify_user
25              end
26            end
27            self.save!
28          end

I want to skip validation on save! on line no 6 rather it is raising the error messages.

bundle exec rake db:migrate /var/lib/gems/2.4.0/gems/json_web_token-0.3.5/lib/json_web_token.rb:36:

Hi for years I have used this website in overcoming many issues. Recently, i decided to setup Catarse and found it to be an uphill battle. Stackflow was the first place i came and though alittle of the issue was discussed, it wasnt on point.I am currently experiencing this issue and cant seem to find any solution. I searched google etc Thanks:

bundle exec rake db:migrate /var/lib/gems/2.4.0/gems/json_web_token-0.3.5/lib/json_web_token.rb:36: warning: already initialized constant JWT /var/lib/gems/2.4.0/gems/jwt-1.5.6/lib/jwt/json.rb:4: warning: previous definition of JWT was here rake aborted! ActiveRecord::AdapterNotSpecified: 'postgresql' database is not configured. Available: ["development", "adapter", "encoding", "database", "pool", "username", "password", "host", "port", "test"] /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/connection_adapters/connection_specification.rb:248:in resolve_symbol_connection' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/connection_adapters/connection_specification.rb:231:inresolve_string_connection' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/connection_adapters/connection_specification.rb:213:in resolve_connection' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/connection_adapters/connection_specification.rb:139:inresolve' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/connection_adapters/connection_specification.rb:151:in block in resolve_all' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/connection_adapters/connection_specification.rb:150:ineach' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/connection_adapters/connection_specification.rb:150:in resolve_all' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/connection_handling.rb:69:inresolve' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/core.rb:46:in configurations=' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/railtie.rb:119:inblock (2 levels) in ' /var/lib/gems/2.4.0/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:38:in instance_eval' /var/lib/gems/2.4.0/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:38:inexecute_hook' /var/lib/gems/2.4.0/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:28:in block in on_load' /var/lib/gems/2.4.0/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:27:ineach' /var/lib/gems/2.4.0/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:27:in on_load' /var/lib/gems/2.4.0/gems/activerecord-4.2.10/lib/active_record/railtie.rb:118:inblock in ' /var/lib/gems/2.4.0/gems/railties-4.2.10/lib/rails/initializable.rb:30:in instance_exec' /var/lib/gems/2.4.0/gems/railties-4.2.10/lib/rails/initializable.rb:30:inrun' /var/lib/gems/2.4.0/gems/railties-4.2.10/lib/rails/initializable.rb:55:in block in run_initializers' /var/lib/gems/2.4.0/gems/railties-4.2.10/lib/rails/initializable.rb:54:inrun_initializers' /var/lib/gems/2.4.0/gems/railties-4.2.10/lib/rails/application.rb:352:in initialize!' /var/lib/gems/2.4.0/gems/railties-4.2.10/lib/rails/railtie.rb:194:inpublic_send' /var/lib/gems/2.4.0/gems/railties-4.2.10/lib/rails/railtie.rb:194:in method_missing' /home/wizard/railsApps/catarse/config/environment.rb:9:in' /var/lib/gems/2.4.0/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:274:in require' /var/lib/gems/2.4.0/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:274:inblock in require' /var/lib/gems/2.4.0/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:240:in load_dependency' /var/lib/gems/2.4.0/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:274:inrequire' /var/lib/gems/2.4.0/gems/railties-4.2.10/lib/rails/application.rb:328:in require_environment!' /var/lib/gems/2.4.0/gems/railties-4.2.10/lib/rails/application.rb:457:inblock in run_tasks_blocks' /var/lib/gems/2.4.0/gems/rake-12.3.1/exe/rake:27:in `' Tasks: TOP => db:migrate => environment (See full trace by running task with --trace)

mercredi 18 avril 2018

Reset ActiveRecord back to default?

Scenario

I have a --mountable Rails engine attached to a parent app. The parent app pulls from a separate data source via its models. With my limited knowledge of Ruby on Rails so far, I used a separate MySQL2 gem connection to load in my engine's data source (not using models thus far in this use case). I know this typically isn't best/standard practice, but I've also got "separate" "pure" Ruby daemons running with the same data source(s), and this solution works for now...

Problem

Except...I've killed the parent app's connection. Upon returning to the parent app (website), it displays ActiveRecord::StatementInvalid in Controller#action ... Mysql2::Error: Table 'foo.bar' doesn't exist: SHOW FULL FIELDS FROM bar.

Possible Solutions(?)

I imagine there's either a way to:

  • Reset the default ActiveRecord connection (reload the ActiveRecord::Base.establish_connection?)
  • If I'm somehow using the same instance as ActiveRecord to create a separate instance to keep my connections separate. In one of my daemons I created a thread pool where each creates and closes its own connection (since one connection can apparently only perform one query at a time), so I know it's possible to call multiple connections at once with this line. But somehow ActiveRecord doesn't play well with this.

Here's my code excerpt from the engine's controller:

def index
  $DBConfig = {host: "blahblah", port: 9999, username: "blahblah", password: "blahblah", database: "blahblah"}
  handler = Mysql2::Client.new($DBConfig)
  data = handler.query("SELECT some FROM data;")
  handler.close
end

I'm also pretty sure I've closed all my existing connections at the ends of all my methods with the handler.close.

Thanks in advance!

How to read cookies in rails app set by some different application

I need to read cookies set by some different application into my rails application. both the application is running under common SSO (authentication) and when the user successfully authenticated he first redirected to the first application (Node/Express app) which write some data into browser cookies and then when the user clicks on some button which loads my rails application. it will create a rails session. I need to set some variables reading from the cookie set by node/express application.

mardi 17 avril 2018

Adding multiple columns dynamically - Ruby

I have the following CSV file:

header 1, header 2, header 3
summin 1, summin 2, summin 3
summin 4, summin 5, summin 6

How would I append a column of data using the CSV class, so the result would look something like:

header 1, header 2, header 3, header 4, header 5
summin 1, summin 2, summin 3, new value 1, new value 2
summin 4, summin 5, summin 6, new value 2, new value 3

Also, new columns are generated as an array using regular expression and on the fly.

Ruby Rails Test Error and Possible Double Gem Install

Going through Agile Ruby Dev Book, and im trying to run bin/rails test for app they have you making thru out the book but getting this crazy long error. Any advice? Tried doing redoing Bundle Install again and that didnt help. Maybe remove this 'capybara' gem?

    $ bin/rails test
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.16.1/lib/bundler/runtime.rb:84:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'capybara'. (Bundler::GemRequireError)
Gem Load Error is: No such file or directory @ rb_sysopen - C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/addressable-2.5.2/data/unicode.data
Backtrace for gem load error is:
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/addressable-2.5.2/lib/addressable/idna/pure.rb:335:in `initialize'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/addressable-2.5.2/lib/addressable/idna/pure.rb:335:in `open'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/addressable-2.5.2/lib/addressable/idna/pure.rb:335:in `<module:IDNA>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/addressable-2.5.2/lib/addressable/idna/pure.rb:20:in `<module:Addressable>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/addressable-2.5.2/lib/addressable/idna/pure.rb:19:in `<top (required)>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `block in require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/addressable-2.5.2/lib/addressable/idna.rb:24:in `rescue in <top (required)>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/addressable-2.5.2/lib/addressable/idna.rb:19:in `<top (required)>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `block in require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/addressable-2.5.2/lib/addressable/uri.rb:20:in `<top (required)>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `block in require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/capybara-3.0.2/lib/capybara/session.rb:4:in `<top (required)>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `block in require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:249:in `load_dependency'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.2.0/lib/active_support/dependencies.rb:283:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/capybara-3.0.2/lib/capybara.rb:393:in `<module:Capybara>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/capybara-3.0.2/lib/capybara.rb:9:in `<top (required)>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:71:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:71:in `block in require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:70:in `require_with_bootsnap_lfi'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:79:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.16.1/lib/bundler/runtime.rb:81:in `block (2 levels) in require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.16.1/lib/bundler/runtime.rb:76:in `each'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.16.1/lib/bundler/runtime.rb:76:in `block in require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.16.1/lib/bundler/runtime.rb:65:in `each'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.16.1/lib/bundler/runtime.rb:65:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bundler-1.16.1/lib/bundler.rb:114:in `require'
C:/Sites/RailsWork/depot/config/application.rb:7:in `<top (required)>'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'

lundi 16 avril 2018

Ruby - Check if string has split keys

I am trying to find if a string has list of keys which are separated with a | delimiter. I currently have following regex but it gives me an error saying it cannot convert Array into string.

Error: `include?': no implicit conversion of Array into String

data.include? keys[5].split("|")

How to store user input in Rails to a csv file

I gather the user input from several questions in my index.html.erb and store them in a string separated by commas. I want to add their answers to my CSV file and store it in my public directory for my Rails app. How can I do this? Here is what I have so far:

//will print out all answers from form and log them
var exportInfo = "";
document.getElementById('submit').addEventListener('click', function() {
  var newAdjustorInfo = document.getElementsByClassName('adjustorInfo');
  for(var i = 0; i<newAdjustorInfo.length; i++){
  exportInfo = exportInfo + newAdjustorInfo[i].value + ", ";
  writeToFile(exportInfo);


}

//This should write to my file, but it does not
function writeToFile(data){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("public/update.csv", 8);
    fh.WriteLine(data);
    fh.Close();
}

I can write to my file using erb tags with this code if it helps:

<% require "csv" %>

<% CSV.open("public/update.csv", "ab") do |csv| %>
<% csv << ["did it work?"] %>
  <% csv << ["did it work?"] %>
<% end %>

});

dimanche 15 avril 2018

How to access variable in an ajax function for timepicker jquery ruby on rails

I'm making a scheduling tool using the jquery-timepicker. I have a @tour that has a start_date and an end_date, that I've passed in through the controller.

In the timepicker, I'd like to limit the hourMin and the hourMax to the current start_date and end_date of @tour, respectively. Right now, I'm getting an error that tour does not exist.

Not really familiar with how ajax code works in terms of getting information from the current start_date and end_date of tour, and how to access this tour variable.

Really appreciate the help in advance!!

<div class="panel-body">
  <%= form_for [@facility, @tour] do |f| %>
    <div class="row">
      <div class="col-md-6">
        <label>Start Availability</label>
        <%= f.text_field :start_date, readonly: true, placeholder: "Start Date", class: "form-control datepicker" %>
      </div>

      <div class="col-md-6">
        <label>End Availability</label>
        <%= f.text_field :end_date, readonly: true, placeholder: "End Date", class: "form-control datepicker"%>
      </div>
    </div>
    <br/>
    <%= f.submit "Save", id: "btn_book", class: "btn btn-normal btn-block", disabled: true %>
  <% end %>
</div>

<script>

  function checkDate(date) {
    dmy = (date.getDate()-1) + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
    return [$.inArray(dmy, unavailableDates) == -1];
  }

  $(function() {
    unavailableDates = [];
    $.ajax({
      url: '<%= preload_facility_path(@facility) %>',
      dataType: 'json',
      success: function(data) {

        $.each(data.unavailable_dates, function (arrID, arrValue) {
            console.log(arrValue)
            unavailableDates.push($.datepicker.formatDate('yy-mm-dd', new Date(arrValue)));
        });
        console.log(unavailableDates)

        var startDateTextBox = $('#tour_start_date');
        var endDateTextBox = $('#tour_end_date');

        $.timepicker.datetimeRange(
          startDateTextBox,
          endDateTextBox,
          {
              dateFormat: "yy-mm-dd",
              timeFormat: "H:mm:ss",
              hourMin: tour.start_date,
              hourMax: tour.end_date,
              stepHour: 1,
              stepMinute: 15,
              range: true,
              minDate: '2d',//how many days after current day
              start: {}, // start picker options
              end: {}, // end picker options
              beforeShowDay: checkDate,
              onSelect: function(selected) {
                $('#btn_book').attr('disabled', false);
              }
          }
        );
      }
    });
  });
</script>

samedi 14 avril 2018

503 service unavailable - Apache/2.4.18 (Ubuntu) Server at Port 80

I am totally new to Ubuntu, Linux, Apache and terminals.. so really hoping if someone could guide me to resolve this issue:

"503 service unavailable - The server is temporarily unable to service your request due... Apache/2.4.18 (Ubuntu) Server at Port 80"

This was caused when I did a system reboot in Ubuntu (via SSH - putty). The reason I did a reebot is because it showed on the system "Required System Reboot" - '108 packahes can be updates'

Googled how to reboot and did $ Sudo Reboot

After reboot my website went down and I am unable to get it up again. Have no clue what happened there.

I am also getting this line in the terminal/Putty '-bash: /home/ubuntu/.rvm/scripts/rvm: No such file or directory'

Please please can someone guide me here. Would be realy great help. I have no dev/Ubuntu experience. I am like totally stuck :(

Thanks, Swaps

vendredi 13 avril 2018

Use Ajax with Ruby to load a Partial within a div

I have the following drop-down menu (screenshot below). What I want to do is to click on each subcategory and show a partial with the information on the gray space below the menu. The menu uses HAML with the following code (excerpt below). Basically, I need to pass a value to the :href attribute and then show the according to partial into the div.

      %li
        %a.dropdown-button.dropdown-menu-kpis{"data-activates" => "SalesDropDown", :href => "#!"}
          %i.material-icons attach_money
          %span
            Sales
            %i.material-icons.right keyboard_arrow_down
        %ul#SalesDropDown.dropdown-content.dropdown-horizontal-list
          %li
            %a.dropdown-content-items{:href => "#general_kpis_sales_aggregate"} Agreggate

Categories Menu and Space to show results

undefined method `group_by_day' for Groupdate + Chartstack graph

I am trying to chart a line graph that displays by orders by the date the were created and I am running into an issue.

Here is the index.html.erb snippet for my home controller causing the error

<%= line_chart @orders.map { |order|
    {name: order.id, data: order.created_at.group_by_day(:created_at, default_value: "missing", time_zone: "Kolkata").count}
} %>

I am receiving the following error:

 undefined method `group_by_day' for "2018-04-12T22:01:52-04:00":String

I have the groupdate and chartkick gems included in my Gemfile, which seems to be the common fix. Any help would be appreciated. Please let me know if you need additional information.

Full Trace:

app/views/home/index.html.erb:14:in `block in _app_views_home_index_html_erb__895458771_51649740'
activeresource (5.0.0) lib/active_resource/collection.rb:8:in `map'
activeresource (5.0.0) lib/active_resource/collection.rb:8:in `map'
app/views/home/index.html.erb:13:in `_app_views_home_index_html_erb__895458771_51649740'
actionview (5.1.6) lib/action_view/template.rb:157:in `block in render'
activesupport (5.1.6) lib/active_support/notifications.rb:168:in `instrument'
actionview (5.1.6) lib/action_view/template.rb:352:in `instrument_render_template'
actionview (5.1.6) lib/action_view/template.rb:155:in `render'
actionview (5.1.6) lib/action_view/renderer/template_renderer.rb:52:in `block (2 levels) in render_template'
actionview (5.1.6) lib/action_view/renderer/abstract_renderer.rb:42:in `block in instrument'
activesupport (5.1.6) lib/active_support/notifications.rb:166:in `block in instrument'
activesupport (5.1.6) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (5.1.6) lib/active_support/notifications.rb:166:in `instrument'
actionview (5.1.6) lib/action_view/renderer/abstract_renderer.rb:41:in `instrument'
actionview (5.1.6) lib/action_view/renderer/template_renderer.rb:51:in `block in render_template'
actionview (5.1.6) lib/action_view/renderer/template_renderer.rb:59:in `render_with_layout'
actionview (5.1.6) lib/action_view/renderer/template_renderer.rb:50:in `render_template'
actionview (5.1.6) lib/action_view/renderer/template_renderer.rb:14:in `render'
actionview (5.1.6) lib/action_view/renderer/renderer.rb:42:in `render_template'
actionview (5.1.6) lib/action_view/renderer/renderer.rb:23:in `render'
actionview (5.1.6) lib/action_view/rendering.rb:103:in `_render_template'
actionpack (5.1.6) lib/action_controller/metal/streaming.rb:217:in `_render_template'
actionview (5.1.6) lib/action_view/rendering.rb:83:in `render_to_body'
actionpack (5.1.6) lib/action_controller/metal/rendering.rb:52:in `render_to_body'
actionpack (5.1.6) lib/action_controller/metal/renderers.rb:141:in `render_to_body'
actionpack (5.1.6) lib/abstract_controller/rendering.rb:24:in `render'
actionpack (5.1.6) lib/action_controller/metal/rendering.rb:36:in `render'
actionpack (5.1.6) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
activesupport (5.1.6) lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
C:/Ruby24-x64/lib/ruby/2.4.0/benchmark.rb:308:in `realtime'
activesupport (5.1.6) lib/active_support/core_ext/benchmark.rb:12:in `ms'
actionpack (5.1.6) lib/action_controller/metal/instrumentation.rb:44:in `block in render'
actionpack (5.1.6) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
activerecord (5.1.6) lib/active_record/railties/controller_runtime.rb:29:in `cleanup_view_runtime'
actionpack (5.1.6) lib/action_controller/metal/instrumentation.rb:43:in `render'
actionpack (5.1.6) lib/action_controller/metal/implicit_render.rb:33:in `default_render'
actionpack (5.1.6) lib/action_controller/metal/basic_implicit_render.rb:4:in `block in send_action'
actionpack (5.1.6) lib/action_controller/metal/basic_implicit_render.rb:4:in `tap'
actionpack (5.1.6) lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'
actionpack (5.1.6) lib/abstract_controller/base.rb:186:in `process_action'
actionpack (5.1.6) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (5.1.6) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (5.1.6) lib/active_support/callbacks.rb:108:in `block in run_callbacks'
shopify_app (8.2.6) lib/shopify_app/controller_concerns/login_protection.rb:15:in `shopify_session'
activesupport (5.1.6) lib/active_support/callbacks.rb:117:in `block in run_callbacks'
activesupport (5.1.6) lib/active_support/callbacks.rb:135:in `run_callbacks'
actionpack (5.1.6) lib/abstract_controller/callbacks.rb:19:in `process_action'
actionpack (5.1.6) lib/action_controller/metal/rescue.rb:20:in `process_action'
actionpack (5.1.6) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
activesupport (5.1.6) lib/active_support/notifications.rb:166:in `block in instrument'
activesupport (5.1.6) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (5.1.6) lib/active_support/notifications.rb:166:in `instrument'
actionpack (5.1.6) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
actionpack (5.1.6) lib/action_controller/metal/params_wrapper.rb:252:in `process_action'
activerecord (5.1.6) lib/active_record/railties/controller_runtime.rb:22:in `process_action'
actionpack (5.1.6) lib/abstract_controller/base.rb:124:in `process'
actionview (5.1.6) lib/action_view/rendering.rb:30:in `process'
actionpack (5.1.6) lib/action_controller/metal.rb:189:in `dispatch'
actionpack (5.1.6) lib/action_controller/metal.rb:253:in `dispatch'
actionpack (5.1.6) lib/action_dispatch/routing/route_set.rb:49:in `dispatch'
actionpack (5.1.6) lib/action_dispatch/routing/route_set.rb:31:in `serve'
actionpack (5.1.6) lib/action_dispatch/journey/router.rb:50:in `block in serve'
actionpack (5.1.6) lib/action_dispatch/journey/router.rb:33:in `each'
actionpack (5.1.6) lib/action_dispatch/journey/router.rb:33:in `serve'
actionpack (5.1.6) lib/action_dispatch/routing/route_set.rb:844:in `call'
omniauth (1.8.1) lib/omniauth/strategy.rb:190:in `call!'
omniauth (1.8.1) lib/omniauth/strategy.rb:168:in `call'
omniauth (1.8.1) lib/omniauth/builder.rb:63:in `call'
rack (2.0.4) lib/rack/etag.rb:25:in `call'
rack (2.0.4) lib/rack/conditional_get.rb:25:in `call'
rack (2.0.4) lib/rack/head.rb:12:in `call'
rack (2.0.4) lib/rack/session/abstract/id.rb:232:in `context'
rack (2.0.4) lib/rack/session/abstract/id.rb:226:in `call'
actionpack (5.1.6) lib/action_dispatch/middleware/cookies.rb:613:in `call'
activerecord (5.1.6) lib/active_record/migration.rb:556:in `call'
actionpack (5.1.6) lib/action_dispatch/middleware/callbacks.rb:26:in `block in call'
activesupport (5.1.6) lib/active_support/callbacks.rb:97:in `run_callbacks'
actionpack (5.1.6) lib/action_dispatch/middleware/callbacks.rb:24:in `call'
actionpack (5.1.6) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.1.6) lib/action_dispatch/middleware/debug_exceptions.rb:59:in `call'
web-console (3.6.0) lib/web_console/middleware.rb:137:in `call_app'
web-console (3.6.0) lib/web_console/middleware.rb:22:in `block in call'
web-console (3.6.0) lib/web_console/middleware.rb:20:in `catch'
web-console (3.6.0) lib/web_console/middleware.rb:20:in `call'
actionpack (5.1.6) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
railties (5.1.6) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.1.6) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (5.1.6) lib/active_support/tagged_logging.rb:69:in `block in tagged'
activesupport (5.1.6) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (5.1.6) lib/active_support/tagged_logging.rb:69:in `tagged'
railties (5.1.6) lib/rails/rack/logger.rb:24:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.1.6) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
actionpack (5.1.6) lib/action_dispatch/middleware/request_id.rb:25:in `call'
rack (2.0.4) lib/rack/method_override.rb:22:in `call'
rack (2.0.4) lib/rack/runtime.rb:22:in `call'
activesupport (5.1.6) lib/active_support/cache/strategy/local_cache_middleware.rb:27:in `call'
actionpack (5.1.6) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.1.6) lib/action_dispatch/middleware/static.rb:125:in `call'
rack (2.0.4) lib/rack/sendfile.rb:111:in `call'
railties (5.1.6) lib/rails/engine.rb:522:in `call'
puma (3.11.3) lib/puma/configuration.rb:225:in `call'
puma (3.11.3) lib/puma/server.rb:624:in `handle_request'
puma (3.11.3) lib/puma/server.rb:438:in `process_client'
puma (3.11.3) lib/puma/server.rb:302:in `block in run'
puma (3.11.3) lib/puma/thread_pool.rb:120:in `block in spawn_thread'

Passenger and Nginx :unix:/tmp/passenger.MGo50AR/agents.s/core failed (2: No such file or directory) while connecting to upstream

I'm new to passenger/ Nginx, I have my rails application running at Nginx and passenger. Some time my application stops working and I got these errors at my nginx error.log file:

App 19637 stderr:  /usr/lib/ruby/vendor_ruby/phusion_passenger/platform_info.rb:363: warning: Insecure world writable dir /usr/local/rvm/gems/ruby-2.4.0 in PATH, mode 042777
App 19637 stderr:  [passenger_native_support.so] trying to compile for the current user (nobody) and Ruby interpreter...
App 19637 stderr:
App 19637 stderr:      (set PASSENGER_COMPILE_NATIVE_SUPPORT_BINARY=0 to disable)
App 19637 stderr:
App 19637 stderr:      Warning: compilation didn't succeed. To learn why, read this file:
App 19637 stderr:
App 19637 stderr:      /tmp/passenger_native_support-2s90v9.log
App 19637 stderr:
App 19637 stderr:  [passenger_native_support.so] finding downloads for the current Ruby interpreter...
App 19637 stderr:
App 19637 stderr:      (set PASSENGER_DOWNLOAD_NATIVE_SUPPORT_BINARY=0 to disable)
App 19637 stderr:
App 19637 stderr:      Could not download https://oss-binaries.phusionpassenger.com/binaries/passenger/by_release/5.2.3/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 404 Not Found
App 19637 stderr:      Trying next mirror...
App 19637 stderr:      Could not download https://s3.amazonaws.com/phusion-passenger/binaries/passenger/by_release/5.2.3/rubyext-ruby-2.4.0-x86_64-linux.tar.gz: The requested URL returned error: 403 Forbidden
App 19637 stderr:  [passenger_native_support.so] will not be used (can't compile or download)


0 11:07:05 [crit] 6591#6591: *217 connect() to unix:/tmp/passenger.MGo50AR/agents.s/core failed (2: No such file or directory) while connecting to upstream, client: 122.160.67.201, server: 58.98.163.42, request: "POST /customerBadgesCounts HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.MGo50AR/agents.s/core:", host: "58.98.163.42:3001"
2018/04/10 11:07:05 [crit] 6591#6591: *217 connect() to unix:/tmp/passenger.MGo50AR/agents.s/core failed (2: No such file or directory) while connecting to upstream, client: 122.160.67.201, server: 58.98.163.42, request: "POST /updated/branches/search HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.MGo50AR/agents.s/core:", host: "58.98.163.42:3001"
2018/04/10 11:07:25 [crit] 6591#6591: *220 connect() to unix:/tmp/passenger.MGo50AR/agents.s/core failed (2: No such file or directory) while connecting to upstream, client: 122.160.67.201, server: 58.98.163.42, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.MGo50AR/agents.s/core:", host: "mydomain.com:3001"
2018/04/10 11:07:42 [crit] 6591#6591: *224 connect() to unix:/tmp/passenger.MGo50AR/agents.s/core failed (2: No such file or directory) while connecting to upstream, client: 122.177.174.65, server: 58.98.163.42, request: "POST /suggestsearch HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.MGo50AR/agents.s/core:", host: "58.98.163.42:3001"
2018/04/10 11:07:42 [crit] 6592#6592: *226 connect() to unix:/tmp/passenger.MGo50AR/agents.s/core failed (2: No such file or directory) while connecting to upstream, client: 122.177.174.65, server: 58.98.163.42, request: "POST /customerBadgesCounts HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.MGo50AR/agents.s/core:", host: "58.98.163.42:3001"
2018/04/10 11:07:42 [crit] 6592#6592: *228 connect() to unix:/tmp/passenger.MGo50AR/agents.s/core failed (2: No such file or directory) while connecting to upstream, client: 122.177.174.65, server: 58.98.163.42, request: "POST /updated/home HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.MGo50AR/agents.s/core:", host: "58.98.163.42:3001"
2018/04/10 11:09:05 [crit] 6591#6591: *230 connect() to unix:/tmp/passenger.MGo50AR/agents.s/core failed (2: No such file or directory) while connecting to upstream, client: 122.160.67.201, server: 58.98.163.42, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.MGo50AR/agents.s/core:", host: "mydomain.com:1111"
2018/04/10 11:09:15 [crit] 6591#6591: *234 connect() to unix:/tmp/passenger.MGo50AR/agents.s/core failed (2: No such file or directory) while connecting to upstream, client: 122.160.67.201, server: 58.98.163.42, request: "GET / HTTP/1.1", upstream: "passenger:unix:/tmp/passenger.MGo50AR/agents.s/core:", host: "mydomain.com:3001"

I'm not getting whats I have made wrong there!

Please help me and suggest a way to moveout from here.

Case-insensitive advanced search in Rails model

How can I apply first example result to second example?

1) Case insensitive search result in Rails model

 self.where("LOWER(shop_name) like ?", "%#{search.downcase}%")

2) advanced search

shops =Shop.where("shop_name LIKE '%#{keywords}%' AND shop_city LIKE '%#{keywords2}%' AND shop_country LIKE '%#{keywords3}%' AND market_type LIKE '%#{keywords4}%'") if keywords||keywords2||keywords3||keywords4.present?

How to add a v-on:change attribute on a select tag using tag helper in rails

I'm trying to ad the v-on:change attribute on a select element generated with select_tag

Something like this

 <%= select_tag "worker_id", options_from_collection_for_select(@workers, "id", "name"), prompt: 'Choose', class: 'form-control', data: { "v-on:change" => "getWorker()" } %>

Also tried

<%= select_tag "worker_id", options_from_collection_for_select(@workers, "id", "name"), prompt: 'Choose', {}, { class: 'form-control', "v-on:change" => "getWorker()" } %>

Still no luck.

mercredi 11 avril 2018

code some one help me with my project i wrote an ordinal code in ruby and am trying to run it in htmll

this is the code that I have its working in ruby but when I try to use it in HTML it field please help

RoR Render errors partial if edit fails

the problem I have is probably easy to solve, although I did a lot of search and cant find a solution.

I have in my _errors.html.erb

<% if obj.errors.any? %>
 <div class="row">
  <div class="col-md-8 col-md-offset-2 col-xs-12">
   <div class="panel panel-danger">
    <div class="panel-heading">
      <h2 class="panel-title">
        <%= pluralize(obj.errors.count, "error") %>
        prohibided this form from being saved:
      </h2>
      <div class="panel-body">
        <ul>
          <% obj.errors.full_messages.each do |msg| %>
           <li><%= msg %></li>
          <% end %>
        </ul>
      </div>
    </div>
   </div>
  </div>
 </div>
<% end %>

Then I have in my edit.html.erb that has a form and:

<%= render 'layouts/errors', obj: @my_obj_here %>

Then in the controller update/create (lets use the update as example):

def update
    if @my_obj_here.update(params[:my_obj_here].permit(:body))
        redirect_to my_path_here_path(@my_obj_here), notice: "Something."
    else
        render 'edit'
    end
 end

The issue happens when I try to update and the submit info is invalid, which will fall into the "render 'edit'"

The errors show correctly (in this case max length 100) but my url changes from: my_obj_here/1/edit to my_obj_here/1

which should not happen.

So next I tried replacing the "render 'edit'" with "redirect_to :back" but this just ignores the <%= render 'layouts/errors', obj: @my_obj_here %> in the edit.html.erb.

Can someone help me out figuring out how to render the same my_obj_here/1/edit? I believe I need to use the "render" my method because the redirect will just skip the errors partial.

Also, in my update method you probably noticed this "if true": redirect_to my_path_here_path(@my_obj_here), notice: "Something." I could the the same and just change my code to: redirect_to :back, :notice => "something." This would work, but does not show the errors as I want them to shown when my the errors partial is used.

how to rename foreign key while creating tables

i have two models for user and account. It is a one to one relationship so i have belongs_to :user in account model.

I have migration script for account table i have t.belongs_to :user, index: true

When i run rake db:migrate it creates column user_id. I want the name as user_account_id.

I tried creating another migration script to change foreign key name from user_id to user_account_id and it works but how can change foreign key name while creating tables so i dont have to add another migration script?

Thanks

mardi 10 avril 2018

blind passthrough has been deprecated

I'm getting following warning at my console:

Passing 'connection' command to redis as is; blind passthrough has been deprecated and will be removed in redis-namespace 2.0 (at /home/tecorb/.rvm/gems/ruby-2.4.1@mproj/gems/sidekiq-5.1.3/lib/sidekiq/web/helpers.rb:152:in `block in redis_connection')

I'm using following gems in my Gemfile:

gem 'sidekiq'
gem "sidekiq-cron", "~> 0.4.5"
gem 'sidekiq-status'
gem 'sidekiq-failures'
gem 'redis-namespace', '~> 1.5'

Please, let me know where I'm lacking the things?

Please help!

Thanks

lundi 9 avril 2018

How to write named scope for Audits which don`t have auditables?

I am using 'Audit' gem in my ruby on rails application. I have used polymorphic association between Audits and my 'Orders'.Now, I want to write a named scope to get only those Audits for which Order is not nil (This is hapening because Order is being deleted after creating the Audit)

<Audit id:110,
auditable_id:4,
auditable_type:"Order",
user_id:1,
user_type:"User",
username:nil,
action:"create",
created_at:"2018-04-07 09:06:20">,
#<Audit id:49,
auditable_id:3,
auditable_type:"Order",
user_id:3,
user_type:"User",
username:nil,
action:"create",
created_at:"2018-04-06 12:28:41">,
#<Audit id:44,
auditable_id:1,
auditable_type:"Order",
user_id:3,
user_type:"User",
username:nil,
action:"create",
created_at:"2018-04-06 12:27:45">

vendredi 6 avril 2018

Cart checkout issue in Spree - Ruby on rails

Steps to produce the issue

Login as user

Add product to the cart

Remove the product from the cart (Product is removed from the cart )

But , the product id still exist in the checkout button in the cart page [modal] , causing error ...

For Instance ,

I have 3 items in my cart with product id's - '400' ,' 401' ,' 402' . Even if i remove the item '400' from the cart.. The checkout form action results in the query as below

SELECT spree_line_items.* FROM spree_line_items WHERE spree_line_items.order_id = 195 AND spree_line_items.id IN (400, 401, 402) ORDER BY spree_line_items.created_at ASC .

And this causes the error page enter image description here

jeudi 5 avril 2018

Ruby-Invalid Signature Error when trying to GET using a module that generates "oauth signature"

Hi I tried to get a oAuth"request_token" to use Nokia health api. https://developer.health.nokia.com/api Since it doesn't provide a client library for Ruby, I had to write code authentication steps. So I also tried to use this code snippet(https://gist.github.com/cheenu/1469815/d2a6c2a2adb7ed7e31179a8259273f115eb62784) which is fit for my project. But no luck!

Whenever I send request using GET, it always sends a response: "Invalid signature" {"status":0,"message":"Invalid signature ....

Is there a correct way to generate OAuth Signature using Ruby? Any help would be appreciated! Regards,


Here I attach the current sourcecode which generates invalid OAuth Signature.

require "cgi"
require 'openssl'
require 'base64'

# Consumer key, provided by Nokia when registering as a partner.
oauth_consumer_key = ENV['nokia_api_key']

# Callback, url encoded.
# This callback will be called after the user has authorized your account
# to access his data (on step 2).
# User id for the user is provided as "userid=" url parameters to the callback.
oauth_callback = 'https://iaura.herokuapp.com/get_auth_token'
# Random string (should be different for every request).
oauth_nonce = rand(10 ** 30).to_s.rjust(30,'0')

# OAuth signature method. Should always be equal to HMAC-SHA1
oauth_signature_method = 'HMAC-SHA1'

# Current date as unix epoch
oauth_timestamp = Time.now.to_i.to_s

# oAuth version. Should always be equal to 1.0
oauth_version = '1.0'

url =  'https://developer.health.nokia.com/account/request_token'
parameters = 'oauth_callback=' + oauth_callback +
             '&oauth_consumer_key=' + oauth_consumer_key +
             '&oauth_nonce=' + oauth_nonce +
             '&oauth_signature_method=' + oauth_signature_method +
             '&oauth_timestamp=' + oauth_timestamp +
             '&oauth_version=' + oauth_version

base_string = 'GET&' + CGI.escape(url) + '&' + CGI.escape(parameters)
secret_key = ENV['nokia_api_secret'] + '&' # Add & at the end of secret_key
oauth_signature = CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1',secret_key, base_string)}"))
request_url = url + '?' + parameters + '&oauth_signature=' + oauth_signature

Defining functionally identical models using similar databases in Rails 3.2

I've got a database with an old schema that I'm going to be migrating data from. The table names and relationships are identical to the database. For some reason when I define the models for the old instance, they are acting as though they're the models of the new database.

from_db.rb

class FromDB < ActiveRecord::Base
 self.abstract_class = true
 establish_connection FROM_DB
end  

from_clip.rb

class FromClip < FromDB
 self.table_name = "clips"
 belongs_to :clippable, polymorphic: true, counter_cache: true
 belongs_to :video, class_name: "FromVideo"
end

clip.rb

 class Clip < ActiveRecord::Base
   belongs_to :clippable, polymorphic: true, counter_cache: true
   belongs_to :video
 end

console

FromClip.first.class.name
FromClip Load (0.2ms)  SELECT `clips`.* FROM `clips` LIMIT 1
=> "Clip" 

All the methods and associations available to FromClip are those in the Clip model rather than the FromClip model, but the instance of FromClip is from the correct database. Thanks for your help

ROR Many to many association ,index page

I'm new to rails and i'm building this application which have 3 models Customer, Ad, CustomerAd where seen is params customer_ad I want CustomerAd to display all Ad and Customer watch them So when Customer click on one of Ads list (show ad) CustomerAd will update seen to true
I'm using:

Customer
  has_many :customer_ads
  has_many :ads through: :customer_ads

Ad
  has_many :customer_ads
  has_many :customers through: :customer_ads

CustomerAd
  belongs_to :customer
  belongs_to :ad

At Ads controller

def show
  ad = Ad.find params[:id]
  Ad.cusomer_ads.update(seen: true)
end

View customer_ad index and controller

              %tbody                  
                - @ads.each do |ad| 
                  - if @customer_ad.seen == true
                    %tr#btn.seen{"data-link" => "#{ad_path(ad)}"}
                      %td
                        = ad.short_description
                        = ad.long_description

                  - else
                    %tr#btn.unseen{"data-link" => "#{ad_path(ad)}"}
                      %td
                        = ad.short_description
                        = ad.long_description

class CustomerAdsController < ApplicationController
  before_action :set_customer_ad, only: [:show, :edit, :update, :destroy]    
  def index        
    @ads = Ad.all
  end

  private
    def set_customer_ad
      @customer_ad = CustomerAd.find(params[:id])
    end


    def customer_ad_params
      params.require(:customer_ad).permit(:customer_id, :ad_id, :bought, :seen)
    end
end

mercredi 4 avril 2018

Page reload in ruby controller function

In my ruby application, i have a controller function to decrease the count of the product quantity in the cart.

order_controller_decorator.rb:

def decrease
  quantity = change_quantity(-1)
  render json: { quantity: quantity, total:current_order.display_item_total }
end 

Here,how can i make my page to reload after the decrease action.

I have tried adding

redirect_to :back

But it didn't work.

Please help me to solve this issue..

Before action at common place in rails controller

I have two base controller classes, one for JSON resource API and other is Application controller API class. I have to add before action for permission check which is applicable for both base classes.

I dont want to repeat the before action code, so wanted to add at common place. If I check there ancestors then I dont see any rails default common classes between them.

Any suggestions? I also want current user in context. What will be good solution to fix this problem?

 class BaseResourceController < JSONAPI::ResourceController
    before_action :check_permissions

    def check_permissions
      current_user.permissions
    end
 end

class ApplicationController < ActionController::API
   before_action :check_permissions

   def check_permissions
     current_user.permissions
   end
end

ActionController::API.ancestors =>

[ActionController::API, Devise::Controllers::UrlHelpers, Devise::Controllers::Helpers, Devise::Controllers::StoreLocation, Devise::Controllers::SignInOut, ActiveRecord::Railties::ControllerRuntime, ActionDispatch::Routing::RouteSet::MountedHelpers, ActionController::RespondWith, ActionController::ParamsWrapper, ActionController::Instrumentation, ActionController::Rescue, ActionController::DataStreaming, ActionController::ForceSSL, AbstractController::Callbacks, ActiveSupport::Callbacks, ActionController::StrongParameters, ActiveSupport::Rescuable, ActionController::BasicImplicitRender, ActionController::ConditionalGet, ActionController::Head, ActionController::Renderers::All, ActionController::Renderers, ActionController::Rendering, ActionController::ApiRendering, ActionController::Redirecting, ActiveSupport::Benchmarkable, AbstractController::Logger, ActionController::UrlFor, AbstractController::UrlFor, ActionDispatch::Routing::UrlFor, ActionDispatch::Routing::PolymorphicRoutes, AbstractController::Rendering, ActionView::ViewPaths, ActionController::Metal, AbstractController::Base, ActiveSupport::Configurable, ActiveSupport::ToJsonWithActiveSupportEncoder, Object, PP::ObjectMixin, ActiveSupport::Dependencies::Loadable, JSON::Ext::Generator::GeneratorMethods::Object, ActiveSupport::Tryable, Kernel, BasicObject]


JSONAPI::ResourceController.ancestors =>

[JSONAPI::ResourceController, JSONAPI::Callbacks, JSONAPI::ActsAsResourceController, ActionController::Base, Devise::Controllers::UrlHelpers, Devise::Controllers::Helpers, Devise::Controllers::StoreLocation, Devise::Controllers::SignInOut, ActiveRecord::Railties::ControllerRuntime, ActionDispatch::Routing::RouteSet::MountedHelpers, ActionController::RespondWith, ActionController::ParamsWrapper, ActionController::Instrumentation, ActionController::Rescue, ActionController::HttpAuthentication::Token::ControllerMethods, ActionController::HttpAuthentication::Digest::ControllerMethods, ActionController::HttpAuthentication::Basic::ControllerMethods, ActionController::DataStreaming, ActionController::Streaming, ActionController::ForceSSL, ActionController::RequestForgeryProtection, AbstractController::Callbacks, ActiveSupport::Callbacks, ActionController::FormBuilder, ActionController::Flash, ActionController::Cookies, ActionController::ParameterEncoding, ActionController::StrongParameters, ActiveSupport::Rescuable, ActionController::ImplicitRender, ActionController::BasicImplicitRender, ActionController::MimeResponds, AbstractController::Caching, AbstractController::Caching::ConfigMethods, AbstractController::Caching::Fragments, ActionController::Caching, ActionController::EtagWithFlash, ActionController::EtagWithTemplateDigest, ActionController::ConditionalGet, ActionController::Head, ActionController::Renderers::All, ActionController::Renderers, ActionController::Rendering, ActionView::Layouts, ActionView::Rendering, ActionController::Redirecting, ActiveSupport::Benchmarkable, AbstractController::Logger, ActionController::UrlFor, AbstractController::UrlFor, ActionDispatch::Routing::UrlFor, ActionDispatch::Routing::PolymorphicRoutes, ActionController::Helpers, AbstractController::Helpers, AbstractController::AssetPaths, AbstractController::Translation, AbstractController::Rendering, ActionView::ViewPaths, ActionController::Metal, AbstractController::Base, ActiveSupport::Configurable, ActiveSupport::ToJsonWithActiveSupportEncoder, Object, PP::ObjectMixin, ActiveSupport::Dependencies::Loadable, JSON::Ext::Generator::GeneratorMethods::Object, ActiveSupport::Tryable, Kernel, BasicObject]

mardi 3 avril 2018

Ruby: How can I properly pass `yield` to Integer#times method?

I am learning Ruby, and for no particular reason, I want to pass the yield object to the Integer#times method so that the yield code block is called a number of times. Here is how I can do it with a named code block:

def withNamedCodeBlock &b
  3.times(&b)
end
withNamedCodeBlock {print "Go "}
#returns Go Go Go

Now, I want to do the same, but without named code blocks; I want to do it with by using the yield keyword. Here is how I tried and failed:

def withYield
  3.times(&yield)
end
withYield {print "Go "}
#returns Go => #<Enumerator: 3:times>
#I expect it to return Go Go Go 

I am still wrapping my head around the various ways to pass code blocks to methods, so additional information regarding that is appreciated.

How to get all records with specific enum in a simple_enum rails 3

spotlight.rb

as_enum :media_type, :image => 0,:video => 1

When I do

Spotlight.last.media_type

return nil. But when I do

 Spotlight.last.image?

it returns true

2nd issue is that it not returns list of all records when I do

Spotlight.images
Spotlight.videos

dimanche 1 avril 2018

How to make the label of ransack checkbox filter clickable

I am building a rails app and I use ransack for search and filtering. In one instance, I use ransack as a checkbox filter. The problem is, a user can only click on the checkbox for the filtering to work. What i want is for the user to be able to click the checkbox label as well and the same filter would apply. This is better for user experience since it may be daunting to always have to click inside of the checkbox. This is the view code for the ransack checkbox filter

  <% new_roles.uniq.each do |new_role| %>
    <div class="styled-input-container">
      <%= check_box_tag('q[role_eq_any][]', new_role) %>
      <%= new_role %>
    </div>
  <% end %>

Rails4 - How to add custom data attributes to body tag in ActiveAdmin

I am using activeadmin gem in my Rails4 app and just wondering how i can add custom attributes on my body tag or custom meta tag in my markup.There are few approaches :-

  1. Override the layout and easily define helper/function to get the meta tag/body custom attributes.
  2. Keep the default settings, just include custom js file in initializers/active_admin.js and let the js make an ajax call and make changes in the body tag and add some attributes.
  3. Is there any other way..an easy one?

Thanks in advance.

How to check if string include symbols?

i have a question: How i can check if a string include symbol? It's looking confusing to me:

class Beba 
def initialize
while true
puts "Qfar emri deshironi ti vnoni bebes?"
 @@emri = gets.chomp.capitalize
  if @@emri.scan(/\d+/).empty? && @@emri.scan(/\/./).empty?
    puts "Ti e emertove beben me emrin: #{@@emri}"
 break 
 else
   puts "Emri nuk mund te jete me numra/simbole, provoni perseri."
end
end
end 
end

As you can see, at if@@emri.scan(/\d+/).empty? && @@emri.scan(/\/./).empty?, i don't know what to do, like which method i can use for @@emri.scan(/\\.\).empty? to check if don't include any symbol. Thank you.