mardi 31 juillet 2018

Skipping skip_before_action :verify_authenticity_token

Rails 3.2

I am trying to do some maintenance on a Rails 3.2 application, and added an API controller.

To avoid getting an invalid CSRF warning, I would like to switch off verification of the authenticity token.

I added the following to the API controller:

skip_before_action :verify_authenticity_token

But I am getting the following error message:

undefined method `skip_before_action' for Api::TicketsController:Class (NoMethodError)

Any ideas?

time format using helper method in ruby on rails

I have time data filed in my table

t.time "start_time"
t.time "end_time"

and when I add the data it displays in this format

Start Time  2000-01-01 06:00:00 UTC
End Time    2000-01-01 08:00:00 UTC

I want only time to be displayed? How do I do that.?

my form is like this

      <div class="form-group row">
         <%= form.label :start_date, class: "control-label text-right col-md-2" %>
         <div class="col-md-4">
           <div class="input-group">
             <%= form.text_field :start_date, id: :course_start_date, value: "#{format_date(form.object.start_date)}", class: "form-control mydatepicker" %>
             <span class="input-group-addon"><i class="icon-calender"></i></span>
         </div>
        </div>
      </div>
      <div class="form-group row">
         <%= form.label :end_date, class: "control-label text-right col-md-2" %>
         <div class="col-md-4">
           <div class="input-group">
              <%= form.text_field :end_date, id: :course_end_date, value: "#{format_date(form.object.end_date)}", class:"form-control mydatepicker" %>
              <span class="input-group-addon"><i class="icon-calender"></i></span>
           </div>
         </div>
      </div>

To display the content only after clicking publish button in Ruby on rails

I have a course module where once created it displays in the front end. I want to add a publish and unpublish button for that. Where only when publish button is clicked it should show the details in the front end.

So for that i added the column in db.

create_table "courses", force: :cascade do |t|
  t.boolean "publish"
  t.boolean "unpublish"
  t.index ["slug"], name: "index_courses_on_slug", unique: true
 end

routes:

resources :courses do
  collection do
    delete 'destroy_multiple'
  end
  member do
    post :copy
    get :publish
    get :unpublish
  end
end

and in course_controller i defined an action

def publish
 publish_course = @course.dup
 publish_course.title = "Copied from:#{@course.id} #{@course.title}"
 respond_to do |format|
   if clone_course.save
     format.html { redirect_to publish_course, notice: "Course was successfully published from #{@course.id}: #{@course.title}." }
     format.json { render :show, status: :created, location: @publish_course }
   else
     format.html {  redirect_to courses_path, alert: "Please try again. Something went wrong.." }
     format.json { render json: publish_course.errors, status: :unprocessable_entity }
   end
  end
end

I need to wire it up with the frontend now. How to display this? Can anyone help?

lundi 30 juillet 2018

Sorting array of hashes based on multiple key/value pairs in Ruby

I have an array of hashes which I have to sort based on four different key value pairs.

Here is the array of hashes, I want First I want to sort based on "to" then based on "from"

[ 
  {
    :title=>"Working as a SSE",
    :organisation=>{:id=>428, :name=>"google"},
    :from=>"2018-6-1",
    :to=>nil
  }, {
    :title=>"Concatenate two video files to single video in players",
    :organisation=>{:id=>197, :name=>"UNFPA"},
    :from=>"2014-1-1",
    :to=>"2015-12-1"
  }, {
    :title=>"Highcharts Demo",
    :organisation=>{:id=>6, :name=>"UNDFS"},
    :from=>"2016-1-1",
    :to=>"2017-6-1"
  }, {
    :title=>"Working as a Judicial Affairs",
    :organisation=>{:id=>427, :name=>"swtp"},
    :from=>"2017-1-1",
    :to=>"2018-6-1"
  }
]

I want the sorting should happen in the following order

  1. First sort is based on "to"
  2. Second sort is based on "from"
  3. Third sort is based on "organisation name"
  4. Finally, sort based on "title"

Can anyone help me sort the array of hashes?

How to integrate whats app apito send and recieve message with rails?

I wanna integrate whats app API to send a message to the user. Please if anyone has done before please help me to do that I am not getting any helpful resource to implement.

Thanks in advance

Get Images from s3 bucket which was previously uploaded through domain xyz.com now I want to get images through abc.com domain how it is possible

I have s3 bucket which is mapped on xyz.com domain now I want to use the same bucket for abc.com domain and want to connect all images which are uploaded through xyz.com.

Is there any way to resolve this thing.

Help will be appreciated.

dimanche 29 juillet 2018

Files saved by carrierwave is being gotten visible to users not logged in

Current Detail

[Env]

nginx puma mysql Rails == 5.1.5

I mounted carrierwave to upload pictures and files in a post.

[Case]

Users not logged in type the file URL in browser, then they can access and view the file.

[Ideal]

Only users logged in is accessible to the file.

The file path is "uploads/post/images/1234(post_id)/sample.png". So far, I locate uploads directory under public, app/assets/, and root directory in vain.

Any answers or suggestions are appreciated.


Source

Rails.application.routes.draw do
  get 'users/index'
  get 'users/show'
  get 'posts/index'

  devise_for :users, module: :users
  resources :users, :only => [:index, :show]

  get "/" => "posts#index"
  get "posts/like_ranking" => "posts#like_rank"
  get "posts/post_count_ranking" => "posts#post_count"
  get "posts/tags_search" => "posts#tags_search"
  get "posts/new" => "posts#new"
  get "posts/:id/reply" => "posts#new"
  post "posts/create" => "posts#create"
  get "posts/:id" => "posts#show"
  get "posts/:id/edit" => "posts#edit"
  post "posts/:id/update" => "posts#update"
  post "posts/:id/destroy" => "posts#destroy"

  get 'tags/:tag', to: 'posts#index', as: :tag

  get "users/:id/likes" => "users#likes"
  get "users/:id/reply" => "users#reply"

  resources :posts, only: %w(index)

  resources :posts, shallow: true do
    resources :likes, only: [:create, :destroy]
  end
end

"

class ImageUploader < CarrierWave::Uploader::Base
  # Choose what kind of storage to use for this uploader:
  storage :file

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

jeudi 26 juillet 2018

how can I learn server side programming and frome where should I start?

I want to begin server side programming and I've lust learned principles of ruby on rails and a little about some programming languages and it is just what I know . I wish to be able to write the logic of webs and mobile applications on server but I don't have any idea about a road map for achieving to this purpose . have you any suggestions and guidance for me? what is the start point for me ? and what things should I learn ?

Read the Spreadsheet cell format in ruby

We have the spreadsheet data with some of the cell data is in bold or italic format. How to read the data in the certain format?

For your reference i have attached the screenshot for the format. Please provide the solution for how to read those bold format data given in the screenshot.Spreadsheet Format

setting default timestamp in simple_form_for rails

My simple_form_for has fields

<div><%= f.input :start_time %></div>
<div><%= f.input :end_time %></div>

start_time and end_time are my database columns in postgresql by default when i open the forms it takes the current time as default as select it on options. How to set the default time which is 02:14(current time for start & end time) in the screensort to 00:00

UI looks like this enter image description here

database column enter image description here

mercredi 25 juillet 2018

Rails goes to show action when I want custom action of open or expired

I am basically trying to do a custom index In my routes.rb I have:

resources :tokens do
  resources :visits
  collection do 
    get :open
    get :expired
  end
end

My routes show as :

 open_tokens GET    /tokens/open(.:format)                                 tokens#open
 expired_tokens GET    /tokens/expired(.:format)                              tokens#expired

I have open and expired defined in my tokens controller

 def open

       @q = Token.open_token.includes(:households, :visits).search(params[:q])
    @tokens = @q.result

       respond_to do |format|
       format.html {render template: 'tokens/open'}
       end
  end

   def expired

  @q = Token.expired_token.includes(:households, :visits).search(params[:q])
    @tokens = @q.result

  respond_to do |format|
      format.html {render template: 'tokens/expired'}
   end
  end

But it goes to my show controller with the following error:

Couldn't find Token with id=open

and it crashes at my Show action:

Better Errors shows the request as:

{"action"=>"show", "controller"=>"tokens", "id"=>"open"}

It seems to me that the action should be open with no parameters

What am I doing wrong?

Set cookie via GrapeApi Ruby on Rails

I have to set secure & http_only cookie from BE for master domain - website.com where those cookies will be also used by subdomains - sub1.website.com, sub2.website.com etc ...

I've tried with cookies, headers['Set-Cookie] but nothing works as expected. Is there any other way to do it via GrapeAPI ?

Any help would be appreciate.

Thanks

mardi 24 juillet 2018

Limitations in passing a huge list of ID array in parameters

I was wondering if there are any issues/consequences when passing a huge chunk of id array via parameter. I understand that there is a browser url limitation but what if I send the request via ajax http get, are there still any possible limitation problems like for example

@users = User.all

my_method_path(:user_ids => @users.pluck(:id))

lundi 23 juillet 2018

Issue writing data to csv file in ruby

I have an issue writing to a CSV file in ruby and can't figure out.

> header = "Full Name, Email, Phone Number" csv_file =
> CSV.open("myfile.csv", "wb") do |csv|
>     csv << header
>     inactive_users_id.each do |inactive_id|  #inactive_users_id is just an array on integers, which represent user id
>         full_name = User.find(inactive_id).full_name
>         email = User.find(inactive_id).email
>         phone_num = User.find(inactive_id).phone_number
>         desired_info = Array.new
>         desired_info.push(full_name)
>         desired_info.push(email)
>         desired_info.push(phone_num)
>         csv << desired_info
>       end 
>    end

I do get following errors:

  1. undefined method `map' for "Full Name, Email, Phone Number":String
  2. if I remove line csv << header my csv file is literally like this: [138] --> which represents the id and other things are not there.

What could be the issue? Thank you!

How to get a tag using Nokogiri

Im doing a simple scraper with Ruby using Nokogiri.

  def processNokogiri

    doc = HTTParty.get("https://www.remotelyawesomejobs.com/jobs")
    @parse_page ||= Nokogiri::HTML(doc)
    @jobs = @parse_page.css(".job").first.at_css "h2"
    puts '*********************'
    puts  @jobs
    puts '*********************'
    flash[:error] = "Noko"

  end

When I print this @jobs, the console shows me:

<h2>
<a itemprop="title" href="/jobs/the-coral-project-mozilla-infrastructure-integration-engineer">Infrastructure &amp; Integration Engineer</a>
<span class="company">
at
<span itemprop="hiringOrganization">The Coral Project @ Mozilla</span>
</span>
</h2>

I want to acess this href="/jobs/the-coral-project-mozilla-infrastructure-integration-engineer" and the name of the Company: The Coral Project @ Mozilla

How can I filter the @jobs entity to acess this data?

Rails 3 Haml 4 Missing Template Error

I am getting a Missing Template error on update action.

I also not sure if this is due to haml.

I am using ruby 2.5.0, rails 3.2.12, HAML 4.0.7 and html-rails 0.4

here is the complete error log.

ActionView::MissingTemplate (Missing template posts/update, application/update with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :slim, :haml]}. Searched in: * "/home/my_rails_app/app/views" * "/usr/local/rvm/gems/ruby-2.5.0/gems/kaminari-0.17.0/app/views" * "/usr/local/rvm/gems/ruby-2.5.0/gems/devise_invitable-1.6.1/app/views" * "/usr/local/rvm/gems/ruby-2.5.0/gems/devise-3.5.10/app/views" ): actionpack (3.2.12) lib/action_view/path_set.rb:58:in `find' actionpack (3.2.12) lib/action_view/lookup_context.rb:109:in `find' actionpack (3.2.12) lib/action_view/renderer/abstract_renderer.rb:3:in `find_template' actionpack (3.2.12) lib/action_view/renderer/template_renderer.rb:34:in `determine_template' actionpack (3.2.12) lib/action_view/renderer/template_renderer.rb:10:in `render' actionpack (3.2.12) lib/action_view/renderer/renderer.rb:36:in `render_template' actionpack (3.2.12) lib/action_view/renderer/renderer.rb:17:in `render' actionpack (3.2.12) lib/abstract_controller/rendering.rb:110:in `_render_template' actionpack (3.2.12) lib/action_controller/metal/streaming.rb:225:in `_render_template' actionpack (3.2.12) lib/abstract_controller/rendering.rb:103:in `render_to_body' actionpack (3.2.12) lib/action_controller/metal/renderers.rb:28:in `render_to_body' actionpack (3.2.12) lib/action_controller/metal/compatibility.rb:50:in `render_to_body' actionpack (3.2.12) lib/abstract_controller/rendering.rb:88:in `render' actionpack (3.2.12) lib/action_controller/metal/rendering.rb:16:in `render' actionpack (3.2.12) lib/action_controller/metal/instrumentation.rb:40:in `block (2 levels) in render' activesupport (3.2.12) lib/active_support/core_ext/benchmark.rb:5:in `block in ms' /usr/local/rvm/rubies/ruby-2.5.0/lib/ruby/2.5.0/benchmark.rb:308:in `realtime' activesupport (3.2.12) lib/active_support/core_ext/benchmark.rb:5:in `ms' actionpack (3.2.12) lib/action_controller/metal/instrumentation.rb:40:in `block in render' actionpack (3.2.12) lib/action_controller/metal/instrumentation.rb:83:in `cleanup_view_runtime' actionpack (3.2.12) lib/action_controller/metal/instrumentation.rb:39:in `render' wicked_pdf (1.1.0) lib/wicked_pdf/pdf_helper.rb:42:in `render_with_wicked_pdf' actionpack (3.2.12) lib/action_controller/metal/implicit_render.rb:10:in `default_render' actionpack (3.2.12) lib/action_controller/metal/implicit_render.rb:5:in `send_action' actionpack (3.2.12) lib/abstract_controller/base.rb:167:in `process_action' actionpack (3.2.12) lib/action_controller/metal/rendering.rb:10:in `process_action' actionpack (3.2.12) lib/abstract_controller/callbacks.rb:18:in `block in process_action' activesupport (3.2.12) lib/active_support/callbacks.rb:458:in `_run__252879580124370649__process_action__1241135802789983149__callbacks' activesupport (3.2.12) lib/active_support/callbacks.rb:405:in `__run_callback' activesupport (3.2.12) lib/active_support/callbacks.rb:385:in `_run_process_action_callbacks' activesupport (3.2.12) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (3.2.12) lib/abstract_controller/callbacks.rb:17:in `process_action' actionpack (3.2.12) lib/action_controller/metal/rescue.rb:29:in `process_action' actionpack (3.2.12) lib/action_controller/metal/instrumentation.rb:30:in `block in process_action' activesupport (3.2.12) lib/active_support/notifications.rb:123:in `block in instrument' activesupport (3.2.12) lib/active_support/notifications/instrumenter.rb:20:in `instrument' activesupport (3.2.12) lib/active_support/notifications.rb:123:in `instrument' actionpack (3.2.12) lib/action_controller/metal/instrumentation.rb:29:in `process_action' actionpack (3.2.12) lib/action_controller/metal/params_wrapper.rb:207:in `process_action' actionpack (3.2.12) lib/abstract_controller/base.rb:121:in `process' actionpack (3.2.12) lib/abstract_controller/rendering.rb:45:in `process' actionpack (3.2.12) lib/action_controller/metal.rb:203:in `dispatch' actionpack (3.2.12) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch' actionpack (3.2.12) lib/action_controller/metal.rb:246:in `block in action' actionpack (3.2.12) lib/action_dispatch/routing/route_set.rb:73:in `dispatch' actionpack (3.2.12) lib/action_dispatch/routing/route_set.rb:36:in `call' journey (1.0.4) lib/journey/router.rb:68:in `block in call' journey (1.0.4) lib/journey/router.rb:56:in `each' journey (1.0.4) lib/journey/router.rb:56:in `call' actionpack (3.2.12) lib/action_dispatch/routing/route_set.rb:601:in `call' mongoid (3.1.7) lib/rack/mongoid/middleware/identity_map.rb:34:in `block in call' mongoid (3.1.7) lib/mongoid/unit_of_work.rb:39:in `unit_of_work' mongoid (3.1.7) lib/rack/mongoid/middleware/identity_map.rb:34:in `call' exception_notification (4.1.1) lib/exception_notification/rack.rb:32:in `call' warden (1.2.7) lib/warden/manager.rb:36:in `block in call' warden (1.2.7) lib/warden/manager.rb:35:in `catch' warden (1.2.7) lib/warden/manager.rb:35:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call' rack (1.4.7) lib/rack/etag.rb:23:in `call' rack (1.4.7) lib/rack/conditionalget.rb:35:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/head.rb:14:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/params_parser.rb:21:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/flash.rb:242:in `call' rack (1.4.7) lib/rack/session/abstract/id.rb:210:in `context' rack (1.4.7) lib/rack/session/abstract/id.rb:205:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/cookies.rb:341:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call' activesupport (3.2.12) lib/active_support/callbacks.rb:405:in `_run__3905902162550555954__call__2684879384500324798__callbacks' activesupport (3.2.12) lib/active_support/callbacks.rb:405:in `__run_callback' activesupport (3.2.12) lib/active_support/callbacks.rb:385:in `_run_call_callbacks' activesupport (3.2.12) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (3.2.12) lib/action_dispatch/middleware/callbacks.rb:27:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/reloader.rb:65:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/remote_ip.rb:31:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call' railties (3.2.12) lib/rails/rack/logger.rb:32:in `call_app' railties (3.2.12) lib/rails/rack/logger.rb:16:in `block in call' activesupport (3.2.12) lib/active_support/tagged_logging.rb:22:in `tagged' railties (3.2.12) lib/rails/rack/logger.rb:16:in `call' request_store (1.4.1) lib/request_store/middleware.rb:19:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/request_id.rb:22:in `call' rack (1.4.7) lib/rack/methodoverride.rb:21:in `call' rack (1.4.7) lib/rack/runtime.rb:17:in `call' activesupport (3.2.12) lib/active_support/cache/strategy/local_cache.rb:72:in `call' rack (1.4.7) lib/rack/lock.rb:15:in `call' actionpack (3.2.12) lib/action_dispatch/middleware/static.rb:62:in `call' railties (3.2.12) lib/rails/engine.rb:479:in `call' railties (3.2.12) lib/rails/application.rb:223:in `call' railties (3.2.12) lib/rails/railtie/configurable.rb:30:in `method_missing' unicorn (5.4.0) lib/unicorn/http_server.rb:606:in `process_client' unicorn (5.4.0) lib/unicorn/http_server.rb:701:in `worker_loop' unicorn (5.4.0) lib/unicorn/http_server.rb:549:in `spawn_missing_workers' unicorn (5.4.0) lib/unicorn/http_server.rb:142:in `start' unicorn (5.4.0) bin/unicorn:126:in `<top (required)>' /usr/local/rvm/gems/ruby-2.5.0/bin/unicorn:23:in `load' /usr/local/rvm/gems/ruby-2.5.0/bin/unicorn:23:in `<main>' /usr/local/rvm/gems/ruby-2.5.0/bin/ruby_executable_hooks:24:in `eval' /usr/local/rvm/gems/ruby-2.5.0/bin/ruby_executable_hooks:24:in `<main>'

vendredi 20 juillet 2018

Jquery 'beforeunload' not working until triggered by any link or button

<script> 
function windowBeforeUnload() {
 return "You sure?";
}
$(window).on('beforeunload',windowBeforeUnload);
</script> 

I posted the following code on a new page in my rails application. I come to the new page via my home page and try reloading the new page or changing the url. There is no pop up message. If i click a link or a button displayed in my new page containing the javascript code, then the 'beforeunload' gets triggered and after this, it starts working for all actions such as changing url , reloading etc. Can someone give me a solution to this and the reason why it is happening so?
P.S. I've also tried using
$(document).ready(function(){...});

Mongoid why should I use update_all instead of simply looping over collection and saving

I am using Mongoid in one of my rails project. I have a very big collection for which I would like to update a specific field of every document. I feel that I should use the update_all method from Mongoid :

Collection.all.update_all(field: new_value)

However in what way is it better than doing :

Collection.all.each do |document|
  document.field = new_value
  document.save
end

Can you please explain what is doing the update_all method that makes it more performant than a simple loop saving every single doc. Do you know any other way/method that could make my code more performant.

mercredi 18 juillet 2018

How do I create migrations for model attributes in rails

I'm having difficulty with bulding attributes within my model. I keep seeing this error

NoMethodError: undefined method `users' for #<ActiveRecord::ConnectionAdapters::SQLite3::TableDefinition:0x00007f9d9ad9df98>

I need attributes that look like this:

#group.rb

class Spree::Group < ActiveRecord::Base
    has_many :users
end

#user_decorator.rb
Spree::User.class_eval do
  belongs_to :group, class_name: "Spree::Group"
end

For group.rb I ran

rails g model Spree::Group

and I got:

class Spree::Group < ApplicationRecord
  has_many :users
end

I'm confused on how to add 'has_many :users' without actually going into the model and inputting it there.

For the user_decorator I'm not sure what that migration would look like. Any help would be fantastic!

How to concat query result of top N records from a group in MYSQL

I have the following query which gives the count of name grouped by user id. I have reached so far but cant go beyond that. I would like to concat the name column of top 2 records per user.

The Query is:

SELECT t.*, 
       IF(@grp = t.user_id, @rowno := @rowno + 1, @rowno := 1) AS rowno, 
       @grp := t.user_id AS u_id 
FROM   (SELECT notes.user_id, 
               t.name        name, 
               Count(t.name) ct 
        FROM   notes 
               INNER JOIN tags t 
                       ON notes.id = t.note_id 
        GROUP  BY notes.user_id, 
                  t.name 
        ORDER  BY notes.user_id, 
                  Count(t.name) DESC) t; 

It gives the following result:

+---------+------------+----+-------+-----+
| user_id | name       | ct | rowno | uid |
+---------+------------+----+-------+-----+
| 282     | realifex   | 1  | 1     | 282 |
+---------+------------+----+-------+-----+
| 282     | clear      | 1  | 2     | 282 |
+---------+------------+----+-------+-----+
| 282     | thinking   | 1  | 3     | 282 |
+---------+------------+----+-------+-----+
| 282     | refreshing | 1  | 4     | 282 |
+---------+------------+----+-------+-----+
| 285     | solid      | 2  | 1     | 285 |
+---------+------------+----+-------+-----+
| 285     | clear      | 1  | 2     | 285 |
+---------+------------+----+-------+-----+
| 285     | thinking   | 1  | 3     | 285 |
+---------+------------+----+-------+-----+
| 287     | holidays   | 3  | 1     | 287 |
+---------+------------+----+-------+-----+
| 287     | Larry      | 3  | 2     | 287 |
+---------+------------+----+-------+-----+
| 287     | travel     | 2  | 3     | 287 |
+---------+------------+----+-------+-----+
| 287     | thinking   | 1  | 4     | 287 |
+---------+------------+----+-------+-----+

I am trying to concat the top 2 results into one column from every user group like this:

+---------+----------------+
| user_id | name           |
+---------+----------------+
| 282     | realifex,clear |
+---------+----------------+
| 285     | solid,   clear |
+---------+----------------+
| 287     | Larry,travel   |
+---------+----------------+

lundi 16 juillet 2018

How to know the page is rendered or redirected in Rails

After clicking on the "Save" button of the account form, the page is rendered to the edit account itself because the validation did not pass successfully. I need to know that the form is redirected or rendered after that validation action.
Please help. Thanks in advance

Uninitialized constant Spree::User after creating attributes in model

I added two attributes to my model:

#group.rb

class Spree::Group < ActiveRecord::Base
    has_many :users
end

#user_decorator.rb
Spree::User.class_eval do
  belongs_to :group, class_name: "Spree::Group"
end

I created a new spree folder in my models directory and created a file for group.rb and user_decorator.rb and added the code then ran:

bundle exec rake:db migrate

I then recived this error:

NameError: uninitialized constant Spree::User

I'm unsure of how to fix this error and wonder if it is because I just added the attributes to my model.

Active Record get all children of children and so on

I am using MongoDb as database.

I want all the children of children and so on. Lets Suppose

  • A has B & C children
  • B has D & E children
  • D has F & G children

So when I query for children node A. I get all the children as output such as B C D E F G

 C = Customer.find_by(:id => "SOME_ID")
 C.children #list all children upto one level

So can anyone suggest me the way, to get recursive children.

Customer model

class Customer

  include Mongoid::Document
  field :email, type: String
  field :referral_id, type: String
  belongs_to :parent, class_name: 'Customer',foreign_key: "referral_id", optional: true
  has_many :children, :class_name => 'Customer', :foreign_key => "referral_id"

end

Can anybody please help me out. Or suggest a way to accomplish this.

Rails Active Records using maximum and minimum simultaneously

Below both the query work fines

Event.joins(:visit).where(:page_id => 3).group(:visit_id).minimum('events.time')

Event.joins(:visit).where(:page_id => 3).group(:visit_id).maximum('events.time')

I want to do find the diff maximum('events.time') - minimum('events.time') and group by visit id

For this I am writing below query

Event.joins(:visit).where(:page_id => 3).group(:visit_id).(maximum('events.time') - minimum('events.time'))

I am getting error, (undefined method maximum for main:Object)

can anyone help me out for this active records query

samedi 14 juillet 2018

how to make a link of 'http' with rails_admin

I am serching below page about how to make a link of 'http' http://api.rubyonrails.org/v5.2.0/classes/ActionDispatch/SSL.html

but I can`t find how to use "http". this is written how to use 'https'

please tell me howt set 'http' for link in the administrator page.

jeudi 12 juillet 2018

ImageMagick Error - Ruby on Rails Windows

Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: ImageMagick/GraphicsMagick is not installed.

I get this Error when trying to upload an Image but I have installed Imagemagick and mini-magick.

Any Ideas?

Ruby Date Time Subtraction

I am trying to calculate the exact duration a process took from some log file result. After parsing the log, I reached at the following stage:

my_array = ["Some_xyz_process", "Start", "2018-07-12", "12:59:53,397", "End", "2018-07-12", "12:59:55,913"]
puts my_array

Some_xyz_process
Start
2018-07-12
12:59:53,397
End
2018-07-12
12:59:55,913

How can I subtract the start date and time with the end date and time in order to retrieve the exact duration the process took?

mercredi 11 juillet 2018

How come my duplicate also effects the original?

I'm trying to add copies to an array with some modification:

  site.pages.dup.each do | page |
    new_page = page.dup
    data = new_page.data
    data['permalink'] = File.join('/app', page.url)
    data['layout'] = 'app'
    site.pages << new_page
  end

  site.pages.each do | page |
    puts page.data
  end 

When I output page.data, the permalinks are different, but data['layout'] is the same for all items in the array. I also tried data = new_page.data.dup and writing out new_page.data in each instance.

Jekyll collection returns the wrong permalink in plugin

I have a jekyll collection that looks like this:

collections:
  docs:
    output: true
    permalink: /:categories/:name

and one document that overrides that permalink:

---
layout: default
permalink: /about_us
title: about
tags:
 - about
 - docs
---

but when I try to output the permalink at the event of site generate in a plugin

  module Jekyll
  class DuplicateCollectionGenerator < Generator
    safe true

    priority :highest

      def generate site
        site.collections['docs'].docs.map do |article|
          puts article.url
        end
      end
    end
  end

I get the wrong one, I get one called /legal/about_us

Why is this happening and what can I do about it?

mardi 10 juillet 2018

Does anyone know how to integrate recaptcha with a bootstrap_form_tag form on rails

I have a rails app and one of the pages has a form. It was designed using the bootstrap_form_tag (which, according to the bootstrap documentation is correctly done because it wasnt built with a model). I am trying to integrate reCaptcha with it, but I am having trouble adding the recaptcha_tags in it. Does anyone know how to integrate recaptcha with a bootstrap_form_tag form on rails?

cannot load such file -- google/apis/sheets_v4 (LoadError)

I'm writing an app that accesses and edits google sheets. I have the same code working in a ruby test file, but when I copy the code line for line to the rails model it throws an error: cannot load such file -- google/apis/sheets_v4 (LoadError)

I have made sure to require google/apis/sheets_v4 and that I'm up to date on 'google-api-client' Both of my files are in the same folder, so they should have access to the same libraries.

The only potential source of error that I have so far is that some part of the app relies on a legacy version of google-api-client, so both 0.4.7 and 0.23.3 are installed. Is there a way to force utilization of one over the other?

The app was developed before my arrival at the company, so I don't know the reasoning for the use of a legacy api (yet).

lundi 9 juillet 2018

How to extract keys from an array

I have an array of tags

[
{"1boy": 0.9390615820884703},
{"solo": 0.9158311486244202},
{"male": 0.6592671275138855},
{"black hair": 0.4281844198703766},

]

How do I extract the string from this array of hashes so that they display as a list:

  • 1boy
  • solo
  • male
  • black hair

vendredi 6 juillet 2018

Remove double quotation marks

using gsub to remove double

a = "5.102"
a.gsub('\"', "") 

result = "5.102"

How can you strip off the quote marks from the return value to get the following?

expected result = 5.102

jeudi 5 juillet 2018

Can I directly append return function calls in Arrays?

I have a function that calls other functions that returns an object. I tried appending the return values of these functions using this format of code:

def get_cinfo(id)
  return Client.find(id)
end

def get_caddress(id)
  return Client.find(id).addresses
end

def get_cpolicies(id)
  return Client.find(id).policies
end

def get_ccontactinfo(id)
  return Client.find(id).contact_informations
end

def generate_client(id)
 client << get_cinfo(id) << get_caddress(id) << get_ccontactinfo(id)
end

where: get_cinfo , get_caddress and get_ccontactinfo are functions returning a single or two instance

The error produced: [get_cinfo...] variable is undefined.

Why is this happening? Are Function calls not directly allowed in appending to arrays?

How do I skip Brakeman checks?

I run a brakeman check on my Rails app (Brakeman 3.4.1, Rails 3.2.21). There is a config file brakeman.yml which contains the following block of code.

---
:skip_checks:
# Skipping this check because of bug in rails 3.2.13
# http://blog.bugsnag.com/2013/03/20/rails-3-2-13-performance-regressions-major-bugs/
- CheckSymbolDoS

I have verified that removing CheckSymbolDoS causes Brakeman to err. However, when I add new checks to the config file - such as CheckMassAssignment - Brakeman still performs the MassAssignment check. Is there something obvious I'm missing...?

Rails+Bootstrap - Display posts in a grid

I'm working on my project and exactly the section of articles. I want to display 8 articles on the main page (2 in a row) and the rest under them - as in the picture (sorry for this drawing)

drawing

Here is the code of this section with articles, they do not want to display after 2 in a row only one by one is

<section class="articles">
<div class="container" >
<% @posts.take(3).each do |post| %>
<div class="row">
<div class="col-md-6">
<figure>
<%= link_to image_tag post.image.url %>
<p class="title">
<figcaption><%= raw link_to post.title, post  %></figcaption>
<figure>
</p>
</div>
</div>
<% end %>
</div>
</section>

mardi 3 juillet 2018

i am trying to do a Pie charts in my ruby on rails app

i am using the gem gruff in window 7 with docker but when i try to write the g.data doesn t allow me for this error:

Magick::ImageMagickError in ArticlesController#index
unable to read font `(null)' @ error/annotate.c/RenderFreetype/1362
Extracted source (around line #32):


puts "mira para que revises"
puts g
g.write("pie_keynote.png")




Rails.root: /example
Application Trace | Framework Trace | Full Trace

app/controllers/articles_controller.rb:32:in `index'

and this is my code of articles_controller line 32:

g = Gruff::Pie.new
g.title = "Visual Pie Graph Test"
g.data 'Fries', 20
g.data 'Hamburgers', 50
puts "mira para que revises"
puts g
g.write("pie_keynote.png")

and i really don t get why the error :(

lundi 2 juillet 2018

ASCII character for 4 space tab

ASCII equivalent for a tab is 0x09.chr but this creates an 8 space tab in a file. How can we have a tab space of 4 spaces instead? Once the file is created we can replace the tabs but is there any way we can have a 4 space tab while the file is created?

Rails Linking to an alternative view other than show

This is Rails 3.2

I have a list of visits and a button that I want to use to call a visit with an alternative view other than show . the button code in haml is:

  link_to 'Checkout', render('checkout'),  class: 'btn btn-mini btn-danger'

The button is in a visits view and the I have checkout.html.haml under visits/views

It seems like render should do it but it doesn't

How can I render a different view other than the default show

Memory increases when upgrade ruby from 1.9.3 to 2.2.10

I was using Ruby 1.9.3 + Rails 3.2.22 in heroku, recently i have upgraded ruby 1.9.3 to 2.2.10 then i could see that memory is growing fast and getting memory quota, we were using performance L dynos and WEB_CONCURRENCY as 80. Will it help anything with GC Tuning?

Before the upgrade memory was reaching 14gb after 9 PM only After the upgrade memory was reaching 14 gb on every 4 hours