mercredi 30 août 2017

Using Zeus for Rails auto-reloading, how do I include classes in extra subfolders?

I'm working on a large Rails 3.2 project. I use Zeus (and sometimes Guard) to auto reload rails so the tests run faster. However, when running certain tests, I get uninitialized constant errors.

It appears that Zeus doesn't like the fact that I've added some subfolders for organizational purposes.

To be specific, under app/models I added a devices subfolder and under that I have other folders that correspond to the namespace of a device.

For example, I might have: app/models/devices/amazon/alexa.rb which would contain the class: Amazon::Alexa. (not an actual example, but indicative of the naming and folder constructs).

I've added the app/models/devices folder to the load path in application.rb:

config.autoload_paths += [ Rails.root.join("app", "models", "devices") ]

This works when I run the Rails app. It also works if I run the specs directly (rspec ...)

But it fails to load constants when I run via Zeus or Guard.

Any suggestions on how to properly configure Zeus/Guard or Rails/Rspec so the load path works and the classes & constants are loaded correctly?

Thanks!

Start Stripe payments after customer information saved [RAILS 5]

I'm building an payment feature to my application and i'm stuck.

So i am on the first checkout page (fill in shipping address and billing address which are part of my Customers model/controller). What i want is when i click on 'submit / go to checkout' that the customer information gets saved AND i start the procedure of checking out with iDeal. As described here (Stripe API -- Stripe API reference ) to accept iDeal payments.

Currently i have this in my StripesController but i can also delete this and the functionality to the Customers controller if need be:

class StripesController < ApplicationController

def create_source
  create_stripe_source
end

private

def create_stripe_source
    Stripe.api_key = "pk_test_asdasn123jlkasdlkmcfake"

    Stripe::Source.create(
      type: "ideal",
      amount: 1000,
      currency: 'eur',
      owner: {
        name: 'John Wicked',
      },
      redirect: {
        return_url: root_url
      }
    )
end
end

I have this in my '_form' as used in my Customers#New

= form_for :customer do |f|
  = f.first_name
  = f.submit

Help would save me big time and thus be much much appreciated.

mardi 29 août 2017

NameError in ArticlesController#create undefined local variable or method `article_params' for #

I am getting this error when I create my articles:

error: NameError in ArticlesController#create undefined local variable or method `article_params' for # Did you mean? article_path

image of error : enter image description here

my code :

class ArticlesController < ApplicationController

   def new
     @article = Article.new 
   end
   def create
  @article = Article.new(article_params)


 if  @article.save
  flash[:notice] = "Article was submitted succsefully"
  redirect_to (@article)
else
   render :new
 end 

    private 
    def article_params 
       params.require(:article).permit(:title, :description)

    end





   end




end 

syntax error, unexpected '=', expecting keyword_end flash [:notice] = "Article was submitted succsefully"

I have this error which is not letting me look at articles that are created

here are my codes article_controller.rb file:

class ArticlesController < ApplicationController

   def new
     @article = Article.new 
   end
   def create
  @article = Article.new(article_params)


 if  @article.save
  flash [:notice] = "Article was submitted succsefully"
  redirect_to_article_path(@article)
else
   render :new
 end 
end 
    private 
    def article_params 
       params.require(:article).permit(:title, :description)

    end





   end




end 

ask me for any other files if you need them

sending Sha256 hash as a URL param as signature for Rails request data

I've noticed that when i send a url like this:

http://localhost:3000/register/register_user/?sig=zaQ/876CwJMEEmrJqAOYHyEKBXy2s03NDmk+3FsXPr4=

what comes through when I use it to compare to the expected result using params[:sig] in the controller is this:

zaQ/876CwJMEEmrJqAOYHyEKBXy2s03NDmk 3FsXPr4=

For some reason the '+' sign that was in the url at the 9th character from the end of the string has been converted to a space.

Not sure why that happens, whether it only happens with + signs or what.

The result returned by Digest::SHA256.base64digest(data) has this plus sign so my validation of the signature is failing.

What's the best way to fix this? Will it suffice in the general case just to convert '+' signs into spaces before the comparison or is the re some less ugly way to address?

how to send UDF in Payumoney?

I have an payment link

http://ift.tt/2vHhmpb

i want to send some additional paramerter like

http://ift.tt/2vpg5rq

so that at the response i can get it and i can identify the transaction better. because payumoeny send email and phone number of that person who enters during transction but i want that a person signs up then he is redirected to payment and i recieve a webhook then i update the transaction details in my database.

Vagrant expand_path: incompatible character encodings: UTF-8 and Windows-1252

I think the problem is because my Pc-User has a "special character" Benny®. This is what the cmd says: enter image description here

This is my Vagrantfile:

Vagrant.configure("2") do |config|
  config.vm.box = "leopard/rwtrusty64"

  config.vm.network "forwarded_port", guest: 3000, host: 3000
  config.vm.network "private_network", ip: "192.168.33.10"
  config.vm.synced_folder "C:/Users/Benny®/Documents/projects", "/home/vagrant/rails"

  config.vm.provider "virtualbox" do |vb|

   vb.memory = "2054"
  end
end

So, what can I do to fix this problem without changing the user.

How to increment the loop if it does not match the id?

I'm working on a code which displays the images from the AWS server. But I'm facing trouble in looping the code.

It works fine for the 1st display but it is not going further (I've to display upto 6 images)

code for this -

def get_image_urls(user)
        user_identifications = user.user_identifications.where(current_flag: true).order(:id_dl)
        urls = []
        keys = []
        if !user_identifications.empty? && !user_identifications.nil?
            user_identifications.each_with_index do |each_id, index|
                obj = S3_BUCKET.object(each_id.aws_key)
                urls << {each_id.id_dl=> obj.presigned_url(:get)}
                keys << {each_id.id_dl=> each_id.aws_key}
            end
        end
        return urls, keys
    end

How to increment the loop based on checking the id and user.identifications value?

migration from rails 3.1 to 3.2 with plugins and fix the deprecation warnings

I am working in a project with Ruby version 1.9.3 and Rails Version 3.1.12. Planning to Migrate the rails Version to 3.2.The issue encountered is with plugins; we have 6 plugins namely,

  • autocomplete
  • filter
  • has_details
  • in_place_editing
  • restful-authentication
  • role_requirement

I was able to upgrade the Gemfile in Dev, But the show stopper found is the plugins, using this doc, http://ift.tt/RTUeAa

I was able to convert the autocomplete to include in the lib/. The main issue is with the others. Rest of them contains some files called

install.rb, Rakefile, templates folders.

is there any way to remove these deprecation warnings, So far, we do not have much test coverage only a low amount.Any Help is appreciated. TIA.

DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://ift.tt/wl0LFP. (called from at /home/rmed176lt/ror/revremit/config/environment.rb:6)

If anybody wants to view the plugin code, Please visit http://ift.tt/2iETJfX

lundi 28 août 2017

How to set infix & prefix indexing in sphinx search

I want to have infix indexing for few fields and prefix indexing for some other fields in my table. Is there a way to do it in sphinx?

I'm looking for options infix_fields & prefix_fields in Sphinx with dict=keywords

Prevent redirect when calling url_for in a rails app

I'm trying to pass a url string to a view from one of my controller methods, like so:

def index
    @locals = {table_cols: $config['global_fields'],
               table_title: $config['main_page']['table_title'],
               ajax: url_for(action: index_data)}} # HERE
end

index_data is a function in my controller that returns some data in JSON format. However, when I navigate to the index page of my application, the browser simply displays the JSON output of index_data.

I'm assuming calling url_for within index is redirecting that page to index_data - is there a way to prevent this and just have url_for return the string, e.g. '/controller/index_data'?

Thanks

Divide ruby code into modules

This is my code for a sales tax problem. http://ift.tt/2xGf2QD I am relatively new to coding and wanted to know how to divide it up into modules. I need 4 modules for input, calculation, round up and output.

dimanche 27 août 2017

Example for deprecation warning

I get the following deprecation warning:

DEPRECATION WARNING: The behavior of `changed?` 
inside of after callbacks will be changing 
in the next version of Rails. 
The new return value will reflect the behavior 
of calling the method after `save` returned 
(e.g. the opposite of what it returns now). 
To maintain the current behavior, use `saved_changes?` instead. 

for this code:

def send_devise_notification(notification, *args)
  # If the record is new or changed then delay the
  # delivery until the after_commit callback otherwise
  # send now because after_commit will not be called.
  if new_record? || changed?
    pending_notifications << [notification, args]
  else
    devise_mailer.send(notification, self, *args).deliver_later
  end
end

Can somebody explain me the Deprecation Warning with an example? I'm not sure if I understand correctly what's meant with The new return value will reflect the behavior of calling the method after "save" returned

Can I now simply replace changed? with saved_changes?? Thanks

Create a stripe source object for iDeal

I'm building an payment feature to my application and i'm stuck.

So i have a products controller where people can customize their own product and once they get to the show page where they see the result they need to have a checkout button.

I'm using stripe API to accept iDeal payments.

Currently i have this in my StripesController:

class StripesController < ApplicationController

def create_source
  create_stripe_source
end

private

def create_stripe_source
    Stripe.api_key = "pk_test_asdasn123jlkasdlkmcfake"

    Stripe::Source.create(
      type: "ideal",
      amount: 1000,
      currency: 'eur',
      owner: {
        name: 'John Wicked',
      },
      redirect: {
        return_url: root_url
      }
    )
end
end

I have this in my Routes.rb

match 'checkout' => 'stripes#create_source', via: [:get, :post]

And this in the view of the my products show action:

%a.btn-primary.btn-success.btn-block{href: checkout_path}
  Checkout

Now what i want to know is how do i accomplish checking out from a button in the show page of my products controller using this api. (Stripe API -- Stripe API reference )

Help would be much much appreciated.

How to pass parameter for validation / treatment in RUBY view

I have a great doubt, I accept tips if they see a better option to do what I want. I have a layout that links to two items the same view >>

<ul class="nav nav-second-level">
  <li>
   <%= link_to backoffice_pedidos_path do %>
     Abertos
   <% end %>
  </li>
  <li>
    <%= link_to backoffice_pedidos_path do %>
      Finalizados
    <% end %>
   </li>
 </ul>

I want to treat in the view the contents of my select, if it clicks "Abertos", it loads the index with a partial _abertos and if it clicks "Finalizados" it loads the index but with another partial _finalizados. Is there any way to pass some parameter in the link_to so that in the view I can handle it to send to the correct partial? Or any tips on how to stay?

index>>

                    <thead>
                    <tr>
                        <th>Pedido</th>
                        <th>Status</th>
                        <th>Data/Hora </th>
                        <th>Produtos </th>                    
                        <th> </th>
                    </tr>
                </thead>
                <tbody> 
                  <% if ??
                  <%= render partial: "backoffice/pedidos/abertos" %>
                  else ??
                  <%= render partial: "backoffice/pedidos/finalizados" %>
                  <% end %>
                </tbody>

partial abertos>>

           <% @pedidos_aguardando.each do |pedido| %>
        <tr> 
          <td><%=pedido.id%></td>
          <td><%=pedido.status%></td>
          <td><%=pedido.created_at%></td>
          <!--<th><%=pedido.produtos.first.produto %></th>-->
          <td><%=pedido.produtos.pluck (:produto)%></td>
          <td width="50px">
              <%= link_to edit_backoffice_pedido_path(pedido), class:"btn btn-primary btn-circle" do %>
                <i class="fa fa-edit"></i>
              <% end %>
          </td>
        </tr>
      <% end %>

Partials fechados

           <% @pedidos_finalizados.each do |pedido| %>
        <tr> 
          <td><%=pedido.id%></td>
          <td><%=pedido.status%></td>
          <td><%=pedido.created_at%></td>
          <!--<th><%=pedido.produtos.first.produto %></th>-->
          <td><%=pedido.produtos.pluck (:produto)%></td>
          <td width="50px">
              <%= link_to edit_backoffice_pedido_path(pedido), class:"btn btn-primary btn-circle" do %>
                <i class="fa fa-edit"></i>
              <% end %>
          </td>
        </tr>
      <% end %>

Controller

def index
@pedidos_aguardando = Pedido.waiting
@pedidos_finalizados = Pedido.ok
 end

Model

class Pedido < ActiveRecord::Base
has_many :produtos

scope :waiting, -> { where(status: 1) }
scope :ok, -> { where(status: 2) }
end

I accept tips and thank you !!

samedi 26 août 2017

Google analytics behaviour API Throws Error

Google API V3 To get Behaviour Overview Data returns Error

ref: http://ift.tt/2w757Wk

Google::Apis::ClientError: dailyLimitExceededUnreg: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.

Unable to find any reference/code to get GA Data in Ruby.

How to set Authentication and create Request. I have secret Key and other Credentials with me.

vendredi 25 août 2017

Formtastic, how to change checkbox wrapping element in `checkboxes`

I use k.input, as: checkboxes to render a list of checkboxes. Currently each checkbox is wrapped in div element with class checkbox, I want to use span instead and add a class name. How can I do it?

jeudi 24 août 2017

Errow when I run rake test in Ruby on Rails

I am getting an error when I try to run a test on my very simple app in ROR. I am taking a course online and I have this very simple database that has two tables: Posts (with title and body) and Comments(with ForeignKey: post_id and body. When I run rake test I get the following error

`.........E

Error: PostsControllerTest#test_should_destroy_post: ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "posts" WHERE "posts"."id" = ? app/controllers/posts_controller.rb:57:in destroy' test/controllers/posts_controller_test.rb:43:inblock (2 levels) in ' test/controllers/posts_controller_test.rb:42:in `block in '

bin/rails test test/controllers/posts_controller_test.rb:41

....

Finished in 12.539965s, 1.1164 runs/s, 1.2759 assertions/s. 14 runs, 16 assertions, 0 failures, 1 errors, 0 skips`

Any help would be appreciated. Thanks.

In ruby on rails with Mysql Connectivity i am facing the following issue:-

Failed to load libmysql.dll from C:\Ruby24\lib\ruby\gems\2.4.0\gems\mysql2-0.4. -x64-mingw32\vendor\libmysql.dll

I tried a lot of method from google and stackoverflow but problem arrive same If someone can help it would be appreciated. Please help me.

mercredi 23 août 2017

NoMethodError in ArticlesController#create undefined method `save' for nil:NilClass

I have a problem with my app, I will now give you the code to from the app and picture of the error, this is my task: I am supposed to create a web app from ruby on rails and the app should create articles and save them to the database.

This is the image of the error: http://ift.tt/2wGEEzJ

my cloud 9 code

routes.rb:

Rails.application.routes.draw do
 # The priority is based upon order of creation: first created -> highest 
 priority.
 # See how all your routes lay out with "rake routes".

 # You can have the root of your site routed with "root"
 # root 'welcome#index'
resources :articles

root 'pages#home'
get 'about', to: 'pages#about'

article.rb:

class Article < ActiveRecord::Base

end

articles_controller.rb:

class ArticlesController < ApplicationController

   def new
     @article = Article.new 
   end
    def create
       #render plain: params[:article].inspect
    @article.save 
    redirect_to_articles_show(@article)
    end
    private 
    def article_params 
   params.require(:article).permit(:title, :description)


   end





end

new.html.erb:

Create an article

<%= form_for @article do |f| %>

<p>
    <%= f.label :title %>

    <%= f.text_field:title %>

</p>
<p>
    <%= f.label :description  %>
    <%= f.text_area :description %>

</p>
<p>
    <%= f.submit %>

</p>
    <% end %>

my migration file:

class CreateArticles < ActiveRecord::Migration
  def change

      create_table :articles do |t|
        t.string :title
        t.text :description

    end
  end
end

my schema.rb:

ActiveRecord::Schema.define(version: 20170820190312) do

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text   "description"
  end

end

ActiveAdmin Scope records by child association

I have a model called Request and it belongs_to polymophic relationship with various request types like Check, Cancellation...etc

I can do Request.first.request and I'll get the instantiated Check, or Cancellation record associated to it.

Within ActiveAdmin I have an index page that shows all the Request records.

I need to scope this index by records which are authenticated by the user.

That means that if a certain user can't manage requests for a Check, they shouldn't be able to see those requests in the request index at all.

I use the Pundit gem.

Ruby : Convert timestamp to date time in given json input

I have a JSON input. I would like to convert all timestamp (createdDate ,modifiedDate) to time in ruby. How do I do that? I tried below methods but dint work

characterList.each { |char| DateTime.strptime(char.try(:getEditInfo).try(:getCreatedDate),%s) }


{"characterList": 
  [
    {"editInfo": 
      {"createdBy": "testname", 
       "createdDate": 1503137795000, 
       "modifiedBy": "testname", 
       "modifiedDate": 1503137795000}, 
     "charInfo": 
      {"charid": "3434", 
       "charDesc": "3434", 
       "status": "ON"}
    }, 
    {"editInfo": 
      {"createdBy": "testname", 
       "createdDate": 1503137795000, 
       "modifiedBy": "testname", 
       "modifiedDate": 1503137795000}, 
     "charInfo": 
      {"charid": "3434   6", 
       "charDesc": "43dfdf", 
       "status": "ON"}
    }, 
    {"editInfo": 
      {"createdBy": "testname", 
       "createdDate": 1503137795000, 
       "modifiedBy": "testname", 
       "modifiedDate": 1503137795000}, 
     "charInfo": 
      {"charid": "4hr_SLA", 
       "charDesc": "sd", 
       "status": "ON"}
    }, 
    {"editInfo": 
      {"createdBy": "testname", 
       "createdDate": 1503137795000, 
       "modifiedBy": "testname", 
       "modifiedDate": 1503137795000}, 
     "charInfo": 
      {"charid": "aaaaaaaaaa", 
       "charDesc": "asdfaadsf   asdfasdf asdf", 
       "status": "ON"}
    }, 
    {"editInfo": 
      {"createdBy": "testname", 
       "createdDate": 1503137795000, 
       "modifiedBy": "testname", 
       "modifiedDate": 1503137795000}, 
     "charInfo": 
      {"charid": "abababab", 
       "charDesc": "abababababab", 
       "status": "ON"}
    }
  ]} 

I am ok converting in 2 like separately for createdDate and modifiedDate. But Im looking for one line solution

Permission denied @ unlink_internal when I run rake db:drop in Rails

I get the following error when I run rake db:drop or rake db:reset

I have tried everything I can find on the internet including restarting the server, restarting my computer, deleting the development.sqlite3 and schema.rb and rerunning migrate. Any help would be appreciated. I am new on ROR. Thanks in advance. I am using Rails 5.1.3 and Ruby 2.4.1.

** Invoke db:drop (first_time)
** Invoke db:load_config (first_time)
** Execute db:load_config
** Invoke db:check_protected_environments (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config
** Execute db:check_protected_environments
** Execute db:drop
** Invoke db:drop:_unsafe (first_time)
** Invoke db:load_config
** Execute db:drop:_unsafe
Permission denied @ unlink_internal - C:/Users/hash/Desktop/Rails_Blog/blog/db/development.sqlite3
Couldn't drop database 'db/development.sqlite3'
rake aborted!
Errno::EACCES: Permission denied @ unlink_internal - C:/Users/hash/Desktop/Rails_Blog/blog/db/development.sqlite3
C:/Ruby24-x64/lib/ruby/2.4.0/fileutils.rb:1340:in `unlink'
C:/Ruby24-x64/lib/ruby/2.4.0/fileutils.rb:1340:in `block in remove_file'
C:/Ruby24-x64/lib/ruby/2.4.0/fileutils.rb:1348:in `platform_support'
C:/Ruby24-x64/lib/ruby/2.4.0/fileutils.rb:1339:in `remove_file'
C:/Ruby24-x64/lib/ruby/2.4.0/fileutils.rb:703:in `remove_file'
C:/Ruby24-x64/lib/ruby/2.4.0/fileutils.rb:506:in `block in rm'
C:/Ruby24-x64/lib/ruby/2.4.0/fileutils.rb:505:in `each'
C:/Ruby24-x64/lib/ruby/2.4.0/fileutils.rb:505:in `rm'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/tasks/sqlite_database_tasks.rb:22:in `drop'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/tasks/database_tasks.rb:144:in `drop'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/tasks/database_tasks.rb:160:in `block in drop_current'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/tasks/database_tasks.rb:304:in `block in each_current_configuration'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/tasks/database_tasks.rb:303:in `each'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/tasks/database_tasks.rb:303:in `each_current_configuration'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/tasks/database_tasks.rb:159:in `drop_current'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/railties/databases.rake:42:in `block (2 levels) in <top (required)>'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `block in execute'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `each'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `execute'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:194:in `block in invoke_with_call_chain'
C:/Ruby24-x64/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:187:in `invoke_with_call_chain'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:180:in `invoke'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activerecord-5.1.3/lib/active_record/railties/databases.rake:38:in `block (2 levels) in <top (required)>'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `block in execute'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `each'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `execute'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:194:in `block in invoke_with_call_chain'
C:/Ruby24-x64/lib/ruby/2.4.0/monitor.rb:214:in `mon_synchronize'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:187:in `invoke_with_call_chain'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/task.rb:180:in `invoke'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/application.rb:152:in `invoke_task'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `each'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block in top_level'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/application.rb:117:in `run_with_threads'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/application.rb:102:in `top_level'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/application.rb:80:in `block in run'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/lib/rake/application.rb:77:in `run'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
C:/Ruby24-x64/bin/rake:22:in `load'
C:/Ruby24-x64/bin/rake:22:in `<main>'
Tasks: TOP => db:drop:_unsafe

String interpolation with hash in ruby

My aim is to replace certain keys in string with values in hash. I am doing it like this

"hello %{name}, today is %{day}" % {name: "Tim", day: "Monday"}

This works fine as it finds all the keys present in the hash to be replaced in the string. If we dont have the key in the hash corresponding to the string. It will throw an error.

"hello %{name}, today is %{day}" % {name: "Tim", city: "Lahore"}

KeyError: key{day} not found

Expected result should be:

"hello Tim, today is %{day}" or "hello Tim, today is "

Can someone guide me in a direction to replace only the matching keys without throwing any errors.

mardi 22 août 2017

manifest requires output filename

I'm using rails 3.0.10 and running rake assets precompile at production server and facing problem as manifest requires output filename.this code is already deployed on heroku server and working fine. Please provide a solution on this.enter image description here

Trying to RVM install Ruby 2.4.1 for Mac El Capitan 10.11.6 and getting

I've looked around to a few different similar problems, and ended up imploding RVM and starting from scratch a few times, and am still getting the same error. rvm version is 1.29.2

Error running '__rvm_make -j 1',
showing last 15 lines of /Users/bsturms/.rvm/log/1503424267_ruby-2.4.1/make.log
compiling ./missing/setproctitle.c
compiling dmyenc.c
linking miniruby
config.status: creating ruby-runner.h
generating encdb.h
dyld: lazy symbol binding failed: Symbol not found: _clock_gettime
  Referenced from: /Users/bsturms/.rvm/src/ruby-2.4.1/./miniruby (which was built for Mac OS X 10.12)
  Expected in: /usr/lib/libSystem.B.dylib

dyld: Symbol not found: _clock_gettime
  Referenced from: /Users/bsturms/.rvm/src/ruby-2.4.1/./miniruby (which was built for Mac OS X 10.12)
  Expected in: /usr/lib/libSystem.B.dylib

make: *** [encdb.h] Trace/BPT trap: 5
++ return 2
There has been an error while running make. Halting the installation. 

How to redirect_to with status code 200 strictly?

  1. I am maintaining a rails 4 application.
  2. In it the front end is designed using angular so all the html pages are present in public and obviously lot of redirect_to in the application.
  3. But the issue is that when ever the rails application do a redirect to it send the status code as 302 but the requirement is status code should be 200 ok only.
  4. Is their a way in rails to strictly send the status code to 200 ok always on all redirect_to. format.html { redirect_to root_path + '#/menu' }

now,How to redirect_to using status code 200 ok

lundi 21 août 2017

How to call a user input in a method in ruby

I'm trying to make this send the user input number to the function but I don't know what I'm doing wrong. Can anyone help me?

puts "\n Amount with decimals:\n "

STDOUT.flush

numb = gets

puts "\n Multiplier:\n "

STDOUT.flush

mult = gets

stoque(0.01, numb, 0.5, mult, 1)

Ruby on Rails installation - An error occurred while installing nio4r

I'm trying to install ROR and starting a first application. I installed it via RailsInstaller.

ruby --version
ruby 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]

I'm using windows 10 64 bits. Actually, the ruby version is 32 bits since I installed it via RailsIntaller (I did not find a 64 bits package on their website)

However, when executing bundle install, the cmd displays the following:

current directory:
C:/dev/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/nio4r-2.1.0/ext/nio4r
C:/dev/RailsInstaller/Ruby2.3.0/bin/ruby.exe -r
./siteconf20170821-16180-18y9lyl.rb extconf.rb --with-cflags=-std=c99
C:/dev/RailsInstaller/Ruby2.3.0/bin/ruby.exe: No such file or directory --
extconf.rb (LoadError)

extconf failed, exit code 1

Gem files will remain installed in
C:/dev/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/nio4r-2.1.0 for
inspection.
Results logged to
C:/dev/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/extensions/x86-mingw32/2.3.0/nio4r-2.1.0/gem_make.out

An error occurred while installing nio4r (2.1.0), and Bundler cannot continue.
Make sure that `gem install nio4r -v '2.1.0'` succeeds before bundling. 

Please note that I tried multiple ways to install ROR (railsIntaller, rubyInstaller+devKit 32/64 bit versions ...) but the error above is the same each time. I also checked environment variables and I confirm that user and system variables point to ruby.exe

Thanks in advance for your help !

Why do i get this error (NoMethodError)

I am having a problem with my ruby on rails cloud 9 code while my task is to create an article from the UI and save it to the database when I hit submit.

This is my image of my problem: http://ift.tt/2fZaxx4

This is my cloud 9 code

routes.rb:

Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest 
priority.
# See how all your routes lay out with "rake routes".

# You can have the root of your site routed with "root"
# root 'welcome#index'
resources :articles

root 'pages#home'
get 'about', to: 'pages#about'

Articles controller (articles_controller.rb):

class ArticlesController < ApplicationController
def new
@article = Article.new 
end
end 

new.html.erb in articles folder in views:

<h1>Create an article</h1>

<%= form_for @article do |f| %>

<p>
    <%= f.label :title %>
    <%= f.text_area :title %>

</p>

<% end %>

Article model (article.rb) :

class Article 

end

I have done a migration and this is my migrate file :

class CreateArticles < ActiveRecord::Migration
def change
@article = Article.new

create_table :articles do |t|
end
end
end

dimanche 20 août 2017

How to setup the devise_token_auth gem?

Someone please can spare a hint how to create a sign up page, login page with this gem? is similar of devise?

the routes are created, and why have to to install rack-cors for this?

samedi 19 août 2017

Ruby on Rails ActionCable and Redis config using Passenger and Nginx

My ActionCable setup works perfectly in the development environment but it fails in production. For the server I am using Nginx and Phussion Passenger to manage my app.

I believe the issue lies within Redis configuration, my config/cable.yml file looks like this

production:
  adapter: redis
  url: redis://lordwaiter.com:6379

local: &local
  adapter: redis
  url: redis://localhost:6379

development: *local
test: *local

I have followed this guide for this implementation

Integrating Action Cable with Passenger + Nginx In the guide the example url for the redis is redis://redis.example.com:6379 so I tried changing mine to redis://redis.lordwaiter.com:6379 that didn't work as well.

My current config throws this error

Redis::CannotConnectError: Error connecting to Redis

I tried placing localhost instead my hostname like redis://localhost:6379 This time my request was handled without throwing any exceptions but I didn't receive any broadcast in the browser.

I think there needs to be a declaration for the redis url in nginx's virtual host file. I am clueless at this moment and I would highly appreciate any guidance over this.

My Nginx virtual host configuration for my host looks like this

server {

    server_name www.lordwaiter.com lordwaiter.com;
    listen 80;
    listen [::]:80;
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # Tell Nginx and Passenger where your app's 'public' directory is
    root /var/www/lordwaiter/code/public;

    # Turn on Passenger
    passenger_enabled on;
    passenger_ruby /usr/local/rvm/gems/ruby-2.4.0/wrappers/ruby;

    ssl on;
    ssl_certificate /etc/ssl/cert_chain.crt;
    ssl_certificate_key /etc/ssl/private.key;

    location /cable {
        passenger_app_group_name lordwaiter_action_cable;
        passenger_force_max_concurrent_requests_per_process 0;
    }


}

Passing parameters from form to controller using RoR

I am new to RoR development and am a little confused about how parameters are passed from a HTML view to the controller. I have seen a few examples online which use a private method like this:

private
def message_params
  params.require(:message).permit(:content)
end

I have been looking for some clarification online as to what this method does and how it works, but I only encounter posts/articles which use the method rather than explain what it does.

I was hoping someone could explain how the method takes(/filters?) values passed via the form via a POST request, what the require and permit keywords mean and how would i change this method to fit my own use.

For example if i needed to get data about a new book would i do this:

private
    def book_params
      params.require(:book_name).require(:ISBN).require(:Author).permit(:Illustrator)
    end

Would the above be valid given that my book object has those fields?

Any clarification would be appreciated.

Thank you.

vendredi 18 août 2017

Convert Time.zone.now to number OLE

I need convert the DateTime to OLE, Actually I have this code

  def self.convert_time(t=42941.6102054745)
    Time.at((t - 25569) * 86400).utc
  end

but this converts to DateTime now I want this solution :

def self.date_time_ole(dt= Time.zone.now)
# her convert to number ole from datetime
end

could you please help me ?

Use Foreign key in where clause in Rails

I have 2 models 1 is request and second is passed

I have a has_one association between requests and passed like this

request has_one status and status belongs_to request

in status I have a boolean field namely "passed"

Now I want to create a scope :passed -> where(request.status.passed=true) inside my requests model.

Any suggestions ?

jeudi 17 août 2017

Return defaul value of hash ruby

I am making a hash like this:

enum_gender={:male=>1,:female=>2, :default_when_fail=>3}

but I need that when I access

enum_gender[:somekey]

It return 3 by default or some value specified

:some_key could be any other :assd, :asf, :asdf

how do I do this ?

mercredi 16 août 2017

How to repeat single hash multiple times in one array?

I want to create dozens of logins that rely on data from this array, logins:

    logins = [
        {
            email: Faker::Internet.email,
            password: "password",
            first_name: Faker::Name.first_name,
            last_name: Faker::Name.last_name 
        },
        {
            email: Faker::Internet.email,
            password: "password",
            first_name: Faker::Name.first_name,
            last_name: Faker::Name.last_name 
        }
    ]

What is a better way of writing this array rather than copy and pasting that hash dozens of times? I am familiar with x.times do but that wouldn't work on an array.

Here's the code where I pass in the logins:

    logins.each do |login|
         li = LoginInformation.new(login: login[:email], password: login[:password])
         if UserManager.save(li)
                company_ids.each do |id|
                  li.contacts.create(first_name: login[:first_name], last_name: login[:last_name], email_address: login[:email], company_id: id, is_employee: true)
                end
         end
    end

How to upload multiple images with Rails 3 + mongoid + carrierwave-mongoid?

I`m newbie in Rails. I try to create form for saving and editing posts (text title, content and images). There are my model for post:

class Post
  include Mongoid::Document
  include Mongoid::Timestamps
  field :title, type: String
  field :content, type: String
  field :image
  field :attachments # - field for files (images) array

  mount_uploader :image, ImageUploader
  mount_uploader :attachments, ImageUploader # - uploader for multiple files
end

It`s my Post controller (works fine for single image upload):

class PostsController < ApplicationController

  def index
    @posts = Post.all
  end

  def create
    p params
    @post = Post.new(posts_params)
    @post.image = posts_params["image"]
    # @post = Post.create!(params)
    # @image = @post.image.build

    if @post.save
      redirect_to "/"
    else
      render action 'new'
    end

    # redirect_to posts_url
  end

  def new
    @post = Post.new
  end

  def posts_params
    params.require(:post).permit(:title, :content, :image, attachments: [])
  end

  def image
    @post = Post.find(params[:id])
    content = @post.image.read
    if stale?(etag: content, last_modified: @post.updated_at.utc, public: true)
      send_data content, type: @post.image.file.content_type, disposition: "inline"
      expires_in 0, public: true
    end
  end
end

But I haven`t any ideas how to process this multiple upload image files.. What I should to do in controller? How to get attachment array in view? Please help.

mardi 15 août 2017

simple_format changes the text itself

In Rails 3.0, the helper method simple_format changes the parameter itself. I expected that it only returns the wrapped text.

2.0.0-p648 :001 > Rails.version
 => "3.0.20"
2.0.0-p648 :002 > s = "Hello"
 => "Hello"
2.0.0-p648 :003 > helper.simple_format(s)
 => "<p>Hello</p>"
2.0.0-p648 :004 > s
 => "<p>Hello</p>"

I checked with Rails 4.2 and it doesn't change the text.

Can someone please explain it?

Sam

Upgrading ruby to 2.3.4 with rails 3.0.5

I am trying to upgrade my rails 3.0.5 application with ruby 2.3.4. Originally it was ruby 1.9.3. I was able to fix most things by updating the gems. However, im stuck on this one problem where when creating new active record objects, the time does not convert properly. For example, Product.new(:bought_on => Date.today), will save the object with bought_on to be the date, not datetime.

I was able to narrow down the problem to the file

activerecord-3.0.20/lib/active_record/attribute_methods/time_zone_conversion.rb

For some reason its not calling these two functions, define_method_attribute and define_method_attribute=.

Any ideas?

lundi 14 août 2017

How to check if nonce has been used?

In my Rails 3.1.5 application, I am using the ims-lti gem to perform third-party authentication. To perform the authentication, three things must be done:

  1. Check that the request signature is correct
  2. Check if the timestamp is too old
  3. Check that the nonce has not been used

The first two are done, but I am having trouble with the nonce check. Most questions I have found deal with generating nonces in Rails, not checking them.

There are several related questions that use the oauth-plugin gem to check the nonce:

Rails oauth-plugin: multiple strategies causes duplicate nonce error

OAuth signature verification fails

return false unless OauthNonce.remember(nonce, timestamp)

Unfortunately, the oauth-plugin gem hasn't been updated since 2013, and is not compatible with the version of the oauth gem required by the lms-lti gem.

It does not appear that the oauth gem supports validating nonces.

Is there a canned way to check the nonce, whether in native Rails or through a gem, or am I relegated to:

  • Creating a nonce table
  • Checking that the nonce is not already in the table
  • Storing the nonce and timestamp in the table
  • Cycling the table to drop entries with an expired timestamp

Intra+Extranet + website

I am building a website with a database. The website is for the customers who get info and hopefully leave their data in my website. I also want to create a intranet+extranet that basically uses the data that customers entered into the website.

Is it normal or best practise that a intra/extranet use the same database as the website? I think the website need its own IP, and the intranet also, maybe with a url prefix like intranet.myurl.com and a local IP, but the website and the intranet; they can use the same database right? Thank you!

Rails console doesn't start - undefiined method cache_control

So I'm trying to run rails console but I get the following error:

/var/lib/gems/2.3.0/gems/actionpack-5.1.3/lib/action_dispatch/http/response.rb:89:in <class:Response>': undefined methodcache_control' for class ActionDispatch::Response' (NameError) from /var/lib/gems/2.3.0/gems/actionpack-5.1.3/lib/action_dispatch/http/response.rb:35:in' from /var/lib/gems/2.3.0/gems/actionpack-5.1.3/lib/action_dispatch/http/response.rb:6:in <top (required)>' from /var/lib/gems/2.3.0/gems/actionpack-5.1.3/lib/action_controller/metal/live.rb:1:inrequire' from /var/lib/gems/2.3.0/gems/actionpack-5.1.3/lib/action_controller/metal/live.rb:1:in <top (required)>' from /var/lib/gems/2.3.0/gems/actionpack-5.1.3/lib/action_controller.rb:4:inrequire' from /var/lib/gems/2.3.0/gems/actionpack-5.1.3/lib/action_controller.rb:4:in <top (required)>' from /var/lib/gems/2.3.0/gems/actionpack-5.1.3/lib/action_controller/railtie.rb:2:inrequire' from /var/lib/gems/2.3.0/gems/actionpack-5.1.3/lib/action_controller/railtie.rb:2:in <top (required)>' from /var/lib/gems/2.3.0/gems/activerecord-5.1.3/lib/active_record/railtie.rb:9:inrequire' from /var/lib/gems/2.3.0/gems/activerecord-5.1.3/lib/active_record/railtie.rb:9:in <top (required)>' from /var/lib/gems/2.3.0/gems/railties-5.1.3/lib/rails/all.rb:14:inrequire' from /var/lib/gems/2.3.0/gems/railties-5.1.3/lib/rails/all.rb:14:in block in <top (required)>' from /var/lib/gems/2.3.0/gems/railties-5.1.3/lib/rails/all.rb:12:ineach' from /var/lib/gems/2.3.0/gems/railties-5.1.3/lib/rails/all.rb:12:in <top (required)>' from /home/isaac/buzzrails/config/application.rb:3:inrequire' from /home/isaac/buzzrails/config/application.rb:3:in <top (required)>' from /var/lib/gems/2.3.0/gems/spring-2.0.2/lib/spring/application.rb:92:inrequire' from /var/lib/gems/2.3.0/gems/spring-2.0.2/lib/spring/application.rb:92:in preload' from /var/lib/gems/2.3.0/gems/spring-2.0.2/lib/spring/application.rb:153:inserve' from /var/lib/gems/2.3.0/gems/spring-2.0.2/lib/spring/application.rb:141:in block in run' from /var/lib/gems/2.3.0/gems/spring-2.0.2/lib/spring/application.rb:135:inloop' from /var/lib/gems/2.3.0/gems/spring-2.0.2/lib/spring/application.rb:135:in run' from /var/lib/gems/2.3.0/gems/spring-2.0.2/lib/spring/application/boot.rb:19:in' from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in require' from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:inrequire' from -e:1:in `'

I've tried restarting spring but it didn't work. Any ideas?

dimanche 13 août 2017

rails how to reject updating when a parameter is missing

i'm kind of new to rails and i want to require a user to input his current_password before updating his infos. I know this can be achieved through devise but i want to do it without devise because i'm having a really hard time modifying the devise.

what i have in mind is something like this:

def update

        @edi_user = EdiUser.find(@trader_edi_user.edi_user_id)
        @edi_user.update_attributes(edi_user_params.reject_if{ |attr| params['current_password'].blank? })

        redirect_to :back
    end

i know this code is wrong, but is this kind of logic possible in rails?

Or can anybody help me how to code the right syntax?

thank you in advance

I have a cloud 9 error while running the app in cloud 9

when I run my app I get this error :

(NoMethodError in Articles#new Showing /home/ubuntu/workspace/yappy/qaucky/app/views/articles/new.html.erb where line #3 raised:

undefined method `model_name' for # Extracted source (around line #3): 1

Create an article

2 3<%= form_for @article do |f| %> 4 5 6<% end %>

this is the image (http://ift.tt/2fDtLYQ)

Rails.root: /home/ubuntu/workspace/yappy/qaucky)

resources :articles

root 'pages#home'
get 'about', to: 'pages#about'

my new.html.erb file:

 <h1>Create an article</h1>
<%= form_for @article do |f| %>
<% end %>

my articles controller file: class ArticlesController < ApplicationController

def new

@article = Article.new 

end





end 

my article.rb file :

class Article 


end

my routes.rb file :

Rails.application.routes.draw do
# The priority is based upon order of creation: first created -> highest 
priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
resources :articles  

root 'pages#home'
get 'about', to: 'pages#about'

# Example of regular route:
#   get 'products/:id' => 'catalog#view'

samedi 12 août 2017

How to convert a ruby array output into a string in JS?

I have this line coming from a helper in the BE and I want to set a variable with that output. No matter what I tried (toString, string interpolation etc) It keeps returning me the error:

Uncaught ReferenceError: a is not defined at eval (eval...

This is my code:

document.myStr = <%= get_str %>

This is the result:

document.myStr = a,b,c;

How to allow users to be able to upload to my google drive in rails app and then provide them a preview link for google doc in the app?

I need my rails app users to be able to upload to my google drive folder. He should click browse file button and after submission, the file should be uploaded to my drive and I should be able to get document preview link and download link for the user in the rails app itself. Please tell me how to proceed with this. I am completely new to rails.

vendredi 11 août 2017

Having to change paths within vendor libraries - Rails Asset Pipeline

What's the best practice for loading third party Javascript libraries (into the asset pipeline) that have references to images and css? My concern is that the libaries internal structure will get changed after loaded into the pipeline. For example:

JS library structure
  - some_js_folder
  - some_css_folder
  - some_image_folder

Will the above structure be maintained or will I need to change the path references in the library itself?

Thanks

Ruby on Rails CSS not loading via assets pipeline

I have searched the web for a solution to this problem and haven't found a solution that works albeit I did find similar problems.

So, I am new to RoR development and this is my first app. I am try to create a page and have so far managed to route to my first page using a controller with an action. The routing works fine.

The problem is with the CSS, I have placed the css in a separate .css file within assets/stylesheets/main.css.

Here it is:

h1 {
   font-size: 100px;
}

I link to all stylesheets using the default method provided by Rails, it is placed in my application.html.erb file like so:

.
.
.
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag 'default', media: 'all', 'data-turbolinks-track': 'reload' %>
.
.
.

From my research, I have learnt that the assets pipeline allows you to place all of your CSS in the assets/stylesheet directory (and JS in the JS directory etc.). Rails should then use these CSS files automatically.

But this isn't working for me as the index.html.erb file stays the same as it would without the main.css when I run the app.

Any help would be appreciated.

Let me know if you require further information.

Thank you.

P.S. Using Rails 5.0.5 and ruby 2.2.6p396 (2016-11-15 revision 56800) [i386-mingw32] on Windows 10

Having with SMTP error in rails application in Rails application?

Having the below error in rails while using the normal smtp:
Net::SMTPFatalError (554 Message rejected: Email address is not verified. The following identities failed the check in region US-EAST: ):
Is their a way in rails to bypass all smtp error so that the application did not get halted show blank page using Rails 2.

sort mini test in rails

hi i'm new to rails and i've done a simple sorting of dates in descending order. and now i need to write a test for it. my controller looks like this

def index
 @article = Article.all.order('date DESC')
end

i tried writing a test but it doesnt work this is my code

def setup
@article1 = articles(:one)
end


test "array should be sorted desc" do
    sorted_array = article1.sort.reverse
    assert_equal article1, sorted_array, "Array sorted"
end

Unable to create record Twilio

Im can't create a twilio record, here's the error message :

Unable to create record: The number +91xxxxxxxxxx is unverified. Trial accounts cannot send messages to unverified numbers; verify +91xxxxxxxxxx at http://ift.tt/1ckpZJB, or purchase a Twilio number to send messages to unverified numbers.

Using test credentials. this Error are through. what is the solution of this error

jeudi 10 août 2017

Document Management System in Rails

I want to create a Document Management interface in Rails which have the windows explorer interface.

Requirements for the interface:

  • Folder manipulation (can create, copy, move or delete folders)
  • File manipulation (can upload, copy, move or delete files)

Good to have:

  • Drag and drop folders and files.

Currently I'm using carrierwave gem to upload files and files and folders will be stored in the

For drag and drop I can use any JS library. But for that interface, does anyone have any idea or have created this in past so that I can get some useful information?

So far, I've found some gems to provide this:

Inline CSS is not working with gem 'htmltopdf'

My requirement is to download docx file and should be open on Microsoft word: I am using below given gems:

gem 'responders' gem 'htmltoword

Find Controller Code from the below:

require 'htmltoword'

class Admin::VisibilitiesController < ApplicationController respond_to :docx, :html, :css,:js

def preview
     @project = Project.find_by(id: params[:id])
     @feeder = Project.find_by(id: params[:id]).form2.last.feeder11s.first
      respond_to do |format|
        format.docx do
        render :docx => "report1_docx",:template => 'admin/visibilities/preview.html.docx.erb', :page_height => 600, :page_width =>345
      end
    end
  end

view file code

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<style type="text/css">
  div.alwaysbreak { page-break-before: always; }
div.nobreak:before { clear:both; }
div.nobreak { page-break-inside: avoid; }
td{padding: 2px 5px;}

</style>
<div style="padding-top:20px;">



<table style="width:800px;margin:0px auto;border:1px solid grey; background: #fff;margin: 0 auto;margin-bottom:30px;padding:10px 20px; ">      
       <tbody>
        <tr>
          <td style="padding: 15px 0 50px;">
            <table style="padding:0px;overflow:hidden;display:table;">
              <tbody>
                <tr>
                  <td style="font-size: 16px;width:100%;font-weight:600">
                    Report No......./...../......./20116-17.....
                  </td>         
                </tr>
                <tr>

                  <td style="font-size: 16px;width:100%;font-weight:600">
                    Dated: ......

                  </td>

                </tr>
              </tbody>  
            </table>
          </td>
        </tr>



        <tr>
         <td style="font-size:28px;font-weight:bold;text-align:center;padding-bottom:20px; font-style: italic;">THIRD PARTY VILLAGE INSPECTION REPORT</td>
        </tr> 
          <tr>
         <td style="font-size:28px;font-weight: bold;text-align:center;padding-bottom:25px; font-style: italic;">OF</td>
        </tr> 
             <tr>
         <td style="font-size:24px;font-weight:400;text-align:center;padding-bottom:25px;">RURAL ELECTRIFICATION WORKS UNDER DEEN DAYAL UPADHYAYA GRAM JYOTI YOJANA (erstwhile RGGVY 12TH PLAN)</td>
        </tr> 
        <tr>
         <td style="font-size:24px;font-weight:400;text-align:center;padding-bottom:20px;">IN</td>
        </tr> 
        <tr>
         <td style="font-size:24px;font-weight:400;text-align:center;padding-bottom:25px;">..............DISTRICT</td>
        </tr> 
        <tr>
         <td style="font-size:24px;font-weight:400;text-align:center;padding-bottom:20px;">SUBMITTED TO</td>
        </tr>     
        <tr>
         <td style="font-size:24px;font-weight:400;text-align:center;padding-bottom:25px;">........................</td>
        </tr>           
        <tr>
           <td style="font-size:24px;font-weight:400;text-align:center;padding-bottom:20px;">SUBMITTED BY </td>
        </tr> 
               <tr>
         <td style="font-size:24px;font-weight:400;text-align:center;padding-bottom:30px;">........................</td>
        </tr>
        <tr>
          <td style="font-style: italic; padding-bottom: 30px; padding-top: 100px;">
            <table style="width: 100%; margin-top: 50px;">
              <tr>
                <td style="font-size:12px;padding-bottom:10px;font-weight:600">Report No (admin)/District(survey)/1st/2016-17/070</td>
                <td style="font-size:12px;padding-bottom:10px;font-weight:600; text-align: right;">Dated: from survey (form1)</td>   
               </tr>
            </table>
          </td>
        </tr>        
        <tr>
          <td style="padding-bottom: 50px;">
            <table style="width: 100%;">
              <tr>
                <td style="font-size:18px;font-weight:600">Location:</td>
                </tr> 
                 <tr>
                 <td style="font-size:16px;font-weight:600">Name of Village     :  <%= @project.form1.try(:village_name) %></td>
                 <tr>
                 <td style="font-size:16px;font-weight:600">Census Code No     :                        <%= @project.form1.try(:census_code_no) %>
</td>
                </tr>

                <tr>
                 <td style="font-size:16px;font-weight:600">Name of Block       : <%= @project.form1.try(:block_name) %></td>
                </tr>
            </table>
          </td>
        </tr>


          </tbody>

    </table>
</body>

</html>

OutPut

enter image description here

rake aborted! ActiveRecord::RecordInvalid: Validation failed: Email can't be blank, Password can't be blank

I am getting an error while doing

heroku run rake db:seed

rake aborted! ActiveRecord::RecordInvalid: Validation failed: Email can't be blank, Password can't be blank

I am using a rails composer app with Devise gem. Any suggestions?!

after_destroy display unscoped value with observer class in rails

I am trying to add to the activity canceled value with after_destoy in observer class, but no value come through to display. if the booking is deleted, the booking flagged as canceled. Any idea how to add the canceled value to the activity with after_destroy?

Many thanks.

This is my observer class:

 class BookingObserver < ActiveRecord::Observer
  def after_destroy(booking)
     Activity.add(booking.venue, booking.created_by, 
     Activity::BOOKING_CANCELLED, booking) unless booking.imported?
  end
  def after_create(booking)

   Activity.add(booking.venue, booking.created_by, 
   Activity::BOOKING_CREATED, booking) unless booking.imported?
  end
 def after_update(booking)
  Activity.add(booking.venue, booking.created_by, 
  Activity::BOOKING_UPDATED, booking) unless booking.imported?
 end
end

undefined method `account' for Twilio

I am using twilio and get: error undefined method `account' for Twilio.

    client = Twilio::REST::Client.new('twilio_sid','twilio_token')
    # Create and send an SMS message
    client.account.sms.messages.create(
    from: "+12345678901",
    to: user.contact,
    body: "Thanks for signing up. To verify your account, please reply HELLO to this message."
)

mercredi 9 août 2017

Ruby On Rails self join associations

I have two tables, and four models in my application. First model is company and it has companies table. Other models are employee,driver and supervisor. I've used single table inheritance in my application.

Company model:

class Company < ApplicationRecord

  has_many :employees

end

And table structure

ID   NAME
1    XXX company

And Employee, Driver and Supervisor models:

class Employee < ApplicationRecord

   belongs_to :company

end

class Chef < Employee


end

class Driver < Employee


end

class Supervisor < Employee


end

And Employees table structure:

ID NAME    COMPANY_ID TYPE
1  Jo      1          Supervisor
2  Jack    1          Driver
3  William 1          Driver
4  Avarell 1          Driver
5  Sam     1          Chef

What I need to do is that I want supervisors to access all drivers that belong to same company via a has_many assocations.

I have tried the following piece of code in supervisor class:

has_many :drivers, ->(supervisor) {where(company: supervisor.company)}

However, rails create the following sql and it is not what I'm expecting

SELECT `employees`.* FROM `employees` WHERE `employees`.`type` IN ('Driver') AND `employees`.`supervisor_id` = 4 AND `employees`.`type` IN ('Driver', 'Supervisor') AND `employees`.`company_id` = 1

I want rails to create such query while it's building the assocation.

SELECT `employees`.* FROM `employees` WHERE `employees`.`type` IN ('Driver') AND `employees`.`company_id` = 1    

Any suggesstions,

Thanks.

upload doc on dropbox how to get url

how to get URL uploaded doc on drop box. and how to store this URL our data base. this is the code   
def passport_upload 
        app_key = ENV['APP_DROPBOX_APP_KEY_DEVELOPMENT'] 
        app_secret = ENV['APP_DROPBOX_APP_SECRET_DEVELOPMENT']  
        flow = DropboxOAuth2FlowNoRedirect.new(app_key, app_secret)
        authorize_url = flow.start()
        client=DropboxClient.new(ENV['APP_DROPBOX_ACCESS_TOKEN_DEVELOPMENT'])
        file = open(params[:doc])
        file_name = params[:doc].original_filename 
        response = client.put_file(file_name, file)
  end   

this is the code how to find the url of uploded doc.

How to pass solr request to markerclusterer api as Maptimize

I am working on Ruby on rails project which contains google maps and solr search and display the results on map using maptimize API for marker and clusters. Instead of using Maptimize, I want to use markerclusterer to show markers and clusters on the map using solr request: I noticed that maptimize api has a method called setSolr that accepts Solr request. is there any similarity between Makerclusterer and Maptimize ?

I want to change Maptimize with Markerclusterer

Best Regards

Can I pass multiple parameters to get multiple result

I am creating an API where I have a table named invoices where customerType is a column. customerType can be of only four possible values IE. PCT, RVN, INT or OTH.

Now, I want to pass URLs like:

http://localhost:3000/api/quatertodate?group-by=customerNumber&customertype=RVN,INT
http://localhost:3000/api/quatertodate?group-by=customerNumber&customertype=RVN,INT,OTH
http://localhost:3000/api/quatertodate?group-by=customerNumber
http://localhost:3000/api/quatertodate?group-by=customerNumber&customertype=PCT
http://localhost:3000/api/quatertodate?group-by=customerNumber&customertype=INT,PCT

But, the issue is whenever I pass a single customertype or no customertype at all, it works but whenever I pass multiple parameters in customertype it returns null when it should be returning combined result of those by performing internal OR query.

In index method of controller I have:

def index
    @invoices=if params[:'group-by'].present?
        if params[:'group-by'].to_s == "customerNumber" 

            if params[:customertype].present?
                Invoice.where(customerType: params[:customertype])
            else
                Invoice.order('customerNumber')
            end
        end
    end 
    render json: {status: 'SUCCESS', messasge: 'LOADED QUATERLY INVOICES', data: @invoices}, status: :ok
end

NOTE: The closest answer I could find is StackOverflow Link. Any help or explanation is much appreciated.

mardi 8 août 2017

ActiveRecord before-transaction callback

Problem: I'm looking for an ActiveRecord (Rails 3.2) callback hook that will execute BEFORE a DB transaction has begun.

If it doesn't exist (and I don't think it does), then I'm looking for any advice in monkey-patching ActiveRecord so that we can implement such a method ourselves.

What I've Tried

Having looked at ActiveRecord docs and playing around with the code, it seems that only 'after_commit' is guaranteed to be executed outside a transaction. Everything else ("before_validation", "before_save", "before_commit") is ran within the transaction. I've tried overriding the 'transaction' method:

class User < ActiveRecord::Base
  included do |base|
    base.instance_eval do
    def before_transaction
      ### DO STUFF
    end

    def transaction(options = {}, &block)
       before_transaction { super(options, &block) }
    end
  end
end

But this is complicated because transaction is a class method and the callback has to be registered per instance of the model. On top of that, it isn't guaranteed to run outside of a DB transaction because it could be nested:

ActiveRecord::Base.transaction do
  ActiveRecord::Base.transaction do
    user.update_attribute(name: "Hodor")
  end
end

Not sure what I want is possible given the way ActiveRecord is implemented, because it may not be possible to know if another transaction has already begun and invoke the callback then. In any case, I thought it's worth asking here.

Background

I'm trying to 'sync' an existing Rails model (let's call it User) to a user service that lives elswhere. The user service should act as the source of truth.

Whenever updates happen to the Rails User model, I would like to validate + commit the change to the user service first, before saving to the DB (which only the Rails project use). The DB for the Rails project then functions as a write-through cache (why a Database for a cache? Legacy code reasons).

If we could call the service BEFORE writing to the DB, we don't have to worry about rolling back the transaction (and dealing with what happens when that rolling back fails!). However, I am hesitant to call the service in the middle of an open DB transaction, which is why I'm looking into whether or not it's possible to build a "before_transaction" callback.

lundi 7 août 2017

How to replace Maptimize with markercluster in maps using solrRequest

Please is there any way to replace maptimize with markerwluster in an old project.

I spent so much time looking at the source code and i didn't find a way to do that.

My map is related to solr and markers and clusters don't appear after longtime. I want to replace this api with markercluster or another free api.

Thank you

Hi guys, i am new to rails,i really want to know how to use checkbox on form_with type

<div class="field">
  <%= form.label :course_type %>
  <%= form.check_box :ctype, {:id => "post_ctype"} %>checkbox 1 
  <%= form.check_box :ctype, {:id => "post_ctype"} %>checkbox 2
</div>

check box is not working properly,so i need a proper syntax for check box in rails,I hope u all

dimanche 6 août 2017

Rails 3 - Splat attr_accessible with Active Record

I'm making typedoptions dynamic by moving them to a new model, as you can see before I was using a constant to make the columns t_a, t_b, t_c accessible with *TYPED_DATA, but now that the model has been migrated, i can't do it anymore. Is there a something I'm missing.

By the way, this fails when I've re-run my specs with FactoryGirl.

class Rules < ActiveRecord::Base
  #TYPED_DATA = %w{a b c}.map { |t| t.prepend('t_').to_sym }

  attr_accessible :name, *Typed.prefixed
end

# typed.rb
class Typed < ActiveRecord::Base
  def self.prefixed
    Typed.pluck(:name).map { |name| name.prepend('t_').to_sym }
  end
end

What is the best option to dynamically expose those attributes?

Selected option with a select_tag

I have a select_tag, like this:

<%= select_tag(:language_ov, options_for_select([['Français', 'FR'],['Anglais', 'EN']], selected: 'FR'), class:"answer language_ov calcul_checkout chosen-select")%>

But if my user don't re-select the choice by default params[:language_ov] is equal to nil

-> I want to give the default value 'FR' for the params[:language_ov] if my user does not select anything.

Unable to deploy rails app on Heroku. Postgresql not detected

I have developed a rails app Todo List but when trying to deploy it on Heroku. I see the database needs to be changed to PostgreSQL. I tried with following changes in my files. But I am unable to trace what could be the possible failure. Searched on various Q&A but couldn't find a solution. Is there any other way deploying on Heroku?

Gemfile:

group :development, :test do
  gem 'sqlite3'
end

group: production do
  gem 'pg'
end

database.yml:

default: &default
adapter: postgresql
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000

development:
<<: *default
database: db/development.sqlite3

test:
<<: *default
database: DB/test.sqlite3

production:
<<: *default
database: db/production.postgresql     

Commands:

$ bundle install 
$ rake db:migrate
rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "db/development.sqlite3" does not exist
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/postgresql_adapter.rb:705:in `rescue in connect'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/postgresql_adapter.rb:701:in `connect'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/postgresql_adapter.rb:220:in `initialize'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/postgresql_adapter.rb:38:in `new'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/postgresql_adapter.rb:38:in `postgresql_connection'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:759:in `new_connection'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:803:in `checkout_new_connection'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:782:in `try_to_checkout_new_connection'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:743:in `acquire_connection'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:500:in `checkout'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:374:in `connection'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:931:in `retrieve_connection'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_handling.rb:116:in `retrieve_connection'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/connection_handling.rb:88:in `connection'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/schema_migration.rb:20:in `table_exists?'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/schema_migration.rb:24:in `create_table'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/migration.rb:1125:in `initialize'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/migration.rb:1007:in `new'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/migration.rb:1007:in `up'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/migration.rb:985:in `migrate'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/tasks/database_tasks.rb:171:in `migrate'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/gems/activerecord-5.1.2/lib/active_record/railties/databases.rake:58:in `block (2 levels) in <top (required)>'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1@global/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/bin/ruby_executable_hooks:15:in `eval'
    /Users/Jeevan/.rvm/gems/ruby-2.4.1/bin/ruby_executable_hooks:15:in `<main>'
    PG::ConnectionBad: FATAL:  database "db/development.sqlite3" does not exist

InvalidURIError when useing httparty post method and get the some field through users

InvalidURIError (bad URI(is not URI?): http://ift.tt/2uwhAPh 8/7?appId=94f56975&appKey=0a0dc2b64f177ab866f0dba59342ffa4) how can solve this error.useing httparty post method.

flight =HTTParty.post("http://ift.tt/2ug15Mk{params[:from]}/to/#{params[:to]}/departing/#{params[:year]}/ #{params[:month]}/#{params[:day]}?appId=94f56975&appKey=0a0dc2b64f177ab866f0dba59342ffa4")

samedi 5 août 2017

Rollback transaction on pressing create button and fetching the value field to insert it into the form_for

ERROR

Started POST "/products" for 127.0.0.1 at 2017-08-05 01:23:20 -0700

Processing by ProductsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"WcfuzGz2ZaEpFmagKYTm3feGTaZxNFPlTkLu/epw7fWObs+pdO4McXw9cLUNjTguav0i97rJR1sLhL5Fk+mk0g==", "product_attribute"=>{"name"=>"RAM 2355 Ghz", "size"=>"4GB", "description"=>"Its a very gooooooooood Ram"}, "value"=>"1", "commit"=>"Create"}

(0.1ms) begin transaction

(0.1ms) rollback transaction

Rendering products/new.html.erb within layouts/application

Rendered products/new.html.erb within layouts/application (2.2ms)

Completed 200 OK in 68ms (Views: 63.6ms | ActiveRecord: 0.1ms)

Description

I'm getting the above error whenever i hit the create button after filling the form.

Products Controller

class ProductsController < ApplicationController

def new
    @product = ProductAttribute.new
    @value = params[:value]
end

def create
    @product = ProductAttribute.new(product_params)
    if @product.save
        redirect_to statics_url
    else
        render 'new'
    end
end


private

def product_params
    params.require(:product_attribute).permit(:name,:value,:size,:description)
end

end

statics Controller

class StaticsController < ApplicationController

def index
    @products = Product.all
end

def new
    @product = Product.new
end

def show
    @product = Product.find(params[:id])
    @attributes = ProductAttribute.where(value: @product.value)
end

def create
    @product = Product.new(product_params)
    if @product.save
        redirect_to root_url
    else
        render 'new'
    end
end

def edit
    @product = Product.find(params[:id])
end

def update
    @product = Product.find(params[:id])
    if @product.update(product_params)
        redirect_to root_url
    else
        render 'edit'
    end
end

private

    def product_params
        params.require(:product).permit(:name,:value)
    end 

end

Static view show.html.erb

<h1>Product listing now</h1>

<% @attributes.each do |attribute| %>
    <li><%= attribute.name%></li>
    <li><%= attribute.value%></li>
    <li><%= attribute.size%></li>
    <li><%= attribute.description%></li>
<% end %>

<%= link_to "Create New Product Attributes", new_product_path(value: 
@product.value) %>

Static view new.html.erb

<h1> New Product Creation </h1>

<%= form_for(@product, url: statics_path) do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <%= f.label :value %>
    <%= f.text_field :value, class: 'form-control' %>

    <%= f.submit "Create", class: "btn btn-primary" %>
<% end %>

Product view new.html.erb

<h1>Add the New Product Attribute</h1>

<%= form_for(@product, url: products_path) do |f|%>
    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <%= hidden_field_tag :value, @value %>

    <%= f.label :size %>
    <%= f.text_field :size, class: 'form-control' %>

    <%= f.label :description %>
    <%= f.text_field :description, class: 'form-control' %>

    <%= f.submit "Create", class: 'btn btn-primary' %>
<% end %>

DESCRIPTION

what i'm trying to do is that, i am passing the value attribute through new_static_path(value: @product.value). I am trying to create a new Product attribute field using the existing value field(which is the primary key). Such as example: Ram(parent field) -> (many child field with common value attributes). And i'm using the hidden_field_tag in the product's view new.html.erb so that it will be derived from controller.(i'm confused about this).

Please help me out with this, i'm a bit new to rails. Any help appreciated, thanks.

vendredi 4 août 2017

Fetch an AWS S3 object to use in Rekognition when uploaded via Carrierwave

I have a Gallery and Attachment models. A gallery has_many attachments and essentially all attachments are images referenced in the ':content' attribute of Attachment.

The images are uploaded using Carrierwave gem and are stored in Aws S3 via fog-aws gem. This works OK. However, I'd like to conduct image recognition to the uploaded images with Amazon Rekognition.

I've installed aws-sdk gem and I'm able to instantiate Rekognition without a problem until I call the detect_labels method at which point I have been unable to use my attached images as arguments of this method.

So fat I've tried:

@attachement = Attachment.first
client = Aws::Rekognition::Client.new
resp = client.detect_labels(
         image: @attachment
       )
# I GET expected params[:image] to be a hash... and got class 'Attachment' instead

I've tried using:

client.detect_labels( image: { @attachment })
client.detect_labels( image: { @attachment.content.url })
client.detect_labels( image: { @attachment.content })

All with the same error. I wonder how can I fetch the s3 object form @attachment and, even if I could do that, how could I use it as an argument in detect_labels.

I've tried also fetching directly the s3 object to try this last bit:

s3 = AWS:S3:Client.new
s3_object = s3.list_objects(bucket: 'my-bucket-name').contents[0]

# and then

client.detect_labels( image: { s3_object })

Still no success...

Any tips?

How to use ClusterMarker with Solr

I am working on rails project that conI want to add clusters and markers on this map ralating it with solr search.

Is there any way to do that ?

Best regards

Prod works for days or weeks then fails with "comparison of Date with ActiveSupport::TimeWithZone"

In a production app, the following code works in dev and (initially) in production:

@employee.ident_expiration_date && @employee.ident_expiration_date < 3.months.from_now

The app is used daily by one or more users. At random intervals, at least a week at most 3 months, this error starts to occur: ActionView::Template::Error (comparison of Date with ActiveSupport::TimeWithZone)

In the console:

>> date = e.ident_expiration_date
=> Sat, 12 Jun 2021

>> date.class
=> Date

>> twz = 3.months.from_now
=> Sat, 04 Nov 2017 10:11:54 CDT -05:00

>> twz.class
=> ActiveSupport::TimeWithZone

>> date < twz
=> false

I thought maybe I was requiring something that might cause that issue... but the only require statement in the entire /app directory is require 'valuable', a gem I wrote. I'm sure that isn't causing the issue.

The process has been alive since I last restarted the app (which caused the issue to disappear.)

product+ 3053 0.0 16.7 1981264 342088 ? Sl Jun16 50:32 puma 2.12.3 (tcp://0.0.0.0:9444) [20170323153916]

So my conclusion at this point is that one of those classes is being polluted by some code that doesn't run very often. I'm have run through the recent history of the app to force this to happen. But I haven't succeeded.

I'm open to any ideas about how this might be happening.

Based on the second reference below, my long-shot answer is to change TimeWithZone to a Date using @employee.ident_expiration_date && @employee.ident_expiration_date < 3.months.from_now.to_date ... but if someone could explain what's happening that would be fantastic.

Versions

Versions:

  • rbx 2.5.2 which is ruby 2.1.0
  • rails 4.2.3
  • Linux version 4.9.15-x86_64-linode81 (maker@build) (gcc version 4.7.2 (Debian 4.7.2-5) )

References

Don't use Date == TimeWithZone, which makes sense.

Date.today > Time.now fails in some situations -- interestingly, I can reproduce their error in irb but not in the Rails console. I assume Rails is doing something to fix this? Could be related but since I can't reproduce it in the console, I'm not sure what to do about it.

Getting a NameError (undefined local variable or method `“_”')

I am trying to initialize a collection through

 c = Collection.new(name: current_user.account.name + "_" + @form.form_name, description: @form.form_name,account: @form.account, data_types: columns, formats: columns)

The thing is that this works locally but on production I get this error

NameError (undefined local variable or method `“_”' for #<FormsController:0x0000001007a890>):

I have been trying to figure this out for the past couple of hours but to no avail

jeudi 3 août 2017

How to track the User Activity in Ruby on Rails

Is there any Gem or Method, which tracks the user behaviour on the site like whether the user has made the purchase of the site by landing on the domain and searching for the product or directly landed on the Product Link and made purchase.

TIA

Rails 3 to Rails 5 migration ActiveRecord issue

Rails upgrade from 2.3.8 to 5.1.2 with Jruby

ActiveRecord issue when upgrading gem 'activerecord-jdbc-adapter'

I started to work as a junior Rails developer and my first task is to update a legacy Rails 2.3.8 app written around 2008 in Jruby 1.5.3 (Ruby 1.8.7) to Rails 5.1.2 in Jruby 9.1.12 (Ruby 2.3.3). It consists of 222 controllers and 122 models, and only spits XML that is consumed by a Java Swing desktop app. Searching I found that the best way to do it, is step by step from one minor version to another correcting all issues in the inter. I reached version 3.0.12 in two weeks leaving the aplication without warnings, but I was asked to go directly to Jruby 9.X.X and Rails 5.1.X. With a few difficulties I get the server up, but when I try to login in the application I got this error. I suspect about the jdbc adapter gem, but any gem below 5.0pre1 works with Rails 5. Could this be only a parsing error from the DB? Should I continue with the cycle I was carrying?

NOTE: There's no test suite for the app, and there are eight modules that override some Rails core methods.

Started POST "/login/login_xml" for 127.0.0.1 at 2017-08-03 12:21:03 -0500
  ActiveRecord::SchemaMigration Load (0.0ms)  SELECT `schema_migrations`.* 
FROM `schema_migrations`

NoMethodError (undefined method `to_sym' for nil:NilClass
Did you mean?  to_s):

activerecord (5.0.4) lib/active_record/attribute_methods/time_zone_conversion.rb:88:in `create_time_zone_conversion_attribute?'
activerecord (5.0.4) lib/active_record/attribute_methods/time_zone_conversion.rb:78:in `block in inherited'
activerecord (5.0.4) lib/active_record/attribute_decorators.rb:62:in `block in matching'
org/jruby/RubyArray.java:2565:in `select'
activerecord (5.0.4) lib/active_record/attribute_decorators.rb:61:in `matching'
activerecord (5.0.4) lib/active_record/attribute_decorators.rb:57:in `decorators_for'
activerecord (5.0.4) lib/active_record/attribute_decorators.rb:48:in `apply'
activerecord (5.0.4) lib/active_record/attribute_decorators.rb:30:in `block in load_schema!'
org/jruby/RubyHash.java:1343:in `each'
activerecord (5.0.4) lib/active_record/attribute_decorators.rb:29:in `load_schema!'
activerecord (5.0.4) lib/active_record/model_schema.rb:455:in `block in load_schema'
C:/jruby-9.1.12.0/lib/ruby/stdlib/monitor.rb:214:in `mon_synchronize'
activerecord (5.0.4) lib/active_record/model_schema.rb:452:in `load_schema'
activerecord (5.0.4) lib/active_record/model_schema.rb:343:in `columns_hash'
activerecord (5.0.4) lib/active_record/querying.rb:41:in `find_by_sql'
activerecord (5.0.4) lib/active_record/relation.rb:702:in `exec_queries'
activerecord (5.0.4) lib/active_record/relation.rb:583:in `load'
activerecord (5.0.4) lib/active_record/relation.rb:260:in `records'
activerecord (5.0.4) lib/active_record/relation/delegation.rb:38:in `map'
activerecord (5.0.4) lib/active_record/migration.rb:1031:in `block in get_all_versions'
activesupport (5.0.4) lib/active_support/deprecation/reporting.rb:36:in `silence'
activesupport (5.0.4) lib/active_support/deprecation/instance_delegator.rb:20:in `silence'
activerecord (5.0.4) lib/active_record/migration.rb:1029:in `get_all_versions'
activerecord (5.0.4) lib/active_record/migration.rb:1043:in `needs_migration?'
activerecord (5.0.4) lib/active_record/migration.rb:573:in `check_pending!'
activerecord (5.0.4) lib/active_record/migration.rb:549:in `call'
actionpack (5.0.4) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call'
activesupport (5.0.4) lib/active_support/callbacks.rb:97:in `__run_callbacks__'
activesupport (5.0.4) lib/active_support/callbacks.rb:750:in `_run_call_callbacks'
activesupport (5.0.4) lib/active_support/callbacks.rb:90:in `run_callbacks'
actionpack (5.0.4) lib/action_dispatch/middleware/callbacks.rb:36:in `call'
actionpack (5.0.4) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.0.4) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
actionpack (5.0.4) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call'
actionpack (5.0.4) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
railties (5.0.4) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.0.4) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (5.0.4) lib/active_support/tagged_logging.rb:69:in `block in tagged'
activesupport (5.0.4) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (5.0.4) lib/active_support/tagged_logging.rb:69:in `tagged'
railties (5.0.4) lib/rails/rack/logger.rb:24:in `call'
sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.0.4) lib/action_dispatch/middleware/request_id.rb:24:in `call'
rack (2.0.3) lib/rack/method_override.rb:22:in `call'
rack (2.0.3) lib/rack/runtime.rb:22:in `call'
activesupport (5.0.4) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
actionpack (5.0.4) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.0.4) lib/action_dispatch/middleware/static.rb:136:in `call'
rack (2.0.3) lib/rack/sendfile.rb:111:in `call'
railties (5.0.4) lib/rails/engine.rb:522:in `call'
puma-3.9.1 (java) lib/puma/configuration.rb:224:in `call'
puma-3.9.1 (java) lib/puma/server.rb:602:in `handle_request'
puma-3.9.1 (java) lib/puma/server.rb:435:in `process_client'
puma-3.9.1 (java) lib/puma/server.rb:299:in `block in run'
puma-3.9.1 (java) lib/puma/thread_pool.rb:120:in `block in spawn_thread'
  Rendering C:/jruby-9.1.12.0/lib/ruby/gems/shared/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
  Rendering C:/jruby-9.1.12.0/lib/ruby/gems/shared/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
  Rendered C:/jruby-9.1.12.0/lib/ruby/gems/shared/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (16.0ms)
  Rendering C:/jruby-9.1.12.0/lib/ruby/gems/shared/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
  Rendered C:/jruby-9.1.12.0/lib/ruby/gems/shared/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (16.0ms)
  Rendering C:/jruby-9.1.12.0/lib/ruby/gems/shared/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
  Rendered C:/jruby-9.1.12.0/lib/ruby/gems/shared/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (12.0ms)
  Rendered C:/jruby-9.1.12.0/lib/ruby/gems/shared/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (142.0ms)

c undefined method `' for #0x5b776b6e>

I have a server with around 50 request per second. And I am getting randomly "NoMethodError" (with very low frequency). The same http request causing "NoMethodError" works fine after restarting server.

Max I could debug is Controller is looking for a action like "" (0 length string). Is 'around_filter' for Application controller buggy?

Here is the backtrace:

NoMethodError error_message="undefined method `' for #<Dash::V2::MyController:0x5b776b6e>

/gems/gems/actionpack-3.2.11/lib/action_controller/metal/implicit_render.rb:4:in `send_action'
/gems/gems/actionpack-3.2.11/lib/abstract_controller/base.rb:167:in `process_action'
/gems/gems/actionpack-3.2.11/lib/action_controller/metal/rendering.rb:10:in `process_action'
/gems/gems/actionpack-3.2.11/lib/abstract_controller/callbacks.rb:18:in `process_action'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:429:in `_run__238585032__process_action__1257768870__callbacks'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:225:in `_conditional_callback_around_1215'
app/controllers/application_controller.rb:90:in `lagging_flag'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:224:in `_conditional_callback_around_1215'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:428:in `_run__238585032__process_action__1257768870__callbacks'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:405:in `__run_callback'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:390:in `_run_process_action_callbacks'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:81:in `run_callbacks'
/gems/gems/actionpack-3.2.11/lib/abstract_controller/callbacks.rb:17:in `process_action'
/gems/gems/actionpack-3.2.11/lib/action_controller/metal/rescue.rb:29:in `process_action'
/gems/gems/actionpack-3.2.11/lib/action_controller/metal/instrumentation.rb:30:in `process_action'
/gems/gems/activesupport-3.2.11/lib/active_support/notifications.rb:123:in `instrument'
/gems/gems/activesupport-3.2.11/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/gems/gems/activesupport-3.2.11/lib/active_support/notifications/instrumenter.rb:19:in `instrument'
/gems/gems/activesupport-3.2.11/lib/active_support/notifications.rb:123:in `instrument'
/gems/gems/actionpack-3.2.11/lib/action_controller/metal/instrumentation.rb:29:in `process_action'
/gems/gems/actionpack-3.2.11/lib/action_controller/metal/params_wrapper.rb:207:in `process_action'
/gems/gems/activerecord-3.2.11/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
/gems/gems/actionpack-3.2.11/lib/abstract_controller/base.rb:121:in `process'
/gems/gems/actionpack-3.2.11/lib/abstract_controller/rendering.rb:45:in `process'
/gems/gems/actionpack-3.2.11/lib/action_controller/metal.rb:203:in `dispatch'
/gems/gems/actionpack-3.2.11/lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
/gems/gems/actionpack-3.2.11/lib/action_controller/metal.rb:246:in `action'
org/jruby/RubyProc.java:281:in `call'
/gems/gems/actionpack-3.2.11/lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
/gems/gems/actionpack-3.2.11/lib/action_dispatch/routing/route_set.rb:36:in `call'
/gems/gems/journey-1.0.4/lib/journey/router.rb:68:in `call'
org/jruby/RubyArray.java:1613:in `each'
/gems/gems/journey-1.0.4/lib/journey/router.rb:56:in `call'
/gems/gems/actionpack-3.2.11/lib/action_dispatch/routing/route_set.rb:601:in `call'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/server_details.rb:12:in `call'
/gems/gems/actionpack-3.2.11/lib/action_dispatch/middleware/head.rb:14:in `call'
/gems/gems/actionpack-3.2.11/lib/action_dispatch/middleware/params_parser.rb:21:in `call'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/json_exception_handler.rb:17:in `call'
/gems/gems/activerecord-3.2.11/lib/active_record/connection_adapters/abstract/connection_pool.rb:479:in `call'
/gems/bundler/gems/rupert-e82e719b3f0c/lib/rupert.rb:23:in `call'
/gems/gems/actionpack-3.2.11/lib/action_dispatch/middleware/callbacks.rb:28:in `call'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:408:in `_run__332066903__call__477376212__callbacks'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:405:in `__run_callback'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:390:in `_run_call_callbacks'
/gems/gems/activesupport-3.2.11/lib/active_support/callbacks.rb:81:in `run_callbacks'
/gems/gems/actionpack-3.2.11/lib/action_dispatch/middleware/callbacks.rb:27:in `call'
/gems/gems/actionpack-3.2.11/lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
/gems/gems/actionpack-3.2.11/lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/request_time_logger.rb:19:in `call'
/gems/gems/activesupport-3.2.11/lib/active_support/core_ext/benchmark.rb:5:in `ms'
/lib/jruby-stdlib-1.7.25.jar!/META-INF/http://ift.tt/2czL0TD `realtime'
/gems/gems/activesupport-3.2.11/lib/active_support/core_ext/benchmark.rb:5:in `ms'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/request_time_logger.rb:18:in `call'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/request_time_logger.rb:16:in `call'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/gc_statistics_logger.rb:14:in `call'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/gc_statistics_logger.rb:13:in `call'
/gems/gems/railties-3.2.11/lib/rails/rack/logger.rb:32:in `call_app'
/gems/gems/railties-3.2.11/lib/rails/rack/logger.rb:16:in `call'
/gems/gems/activesupport-3.2.11/lib/active_support/tagged_logging.rb:22:in `tagged'
/gems/gems/railties-3.2.11/lib/rails/rack/logger.rb:16:in `call'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/request_id_generator.rb:33:in `call'
/gems/gems/rack-1.4.5/lib/rack/methodoverride.rb:21:in `call'
/gems/gems/rack-1.4.5/lib/rack/runtime.rb:17:in `call'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/log_flusher.rb:9:in `call'
/gems/bundler/gems/responseable-eac8dfa003a4/lib/responseable/middleware_start_header.rb:11:in `call'
/gems/gems/railties-3.2.11/lib/rails/engine.rb:479:in `call'
/gems/gems/railties-3.2.11/lib/rails/application.rb:223:in `call'
file:/lib/jruby-rack-1.1.19.jar!/rack/handler/servlet.rb:22:in `call'

Brief of ApplicationController:

around_filter :lagging_flag

def lagging_flag
    if params[:lagging] && params[:lagging].is_a?( Hash )
      Feature.override_lagging_config(params[:lagging]) do
        yield
      end
    else
      yield # => line number 90
    end
end

how can i create a form without use resources(action :new, :create ) in rails

This is my controller

class SchoolsController < ApplicationController
  def teacher
    @teacher = Teacher.new
  end

  def form_create
    @teacher = Teacher.new(teacher_params)
      if  teacher.save
         redirect_to schools_teacher_path
      else
         flash[:notice] = "error"
      end
 end
 private
  def teacher_params
    params.require(:teacher).permit(:name)
  end

end

This is my views/schools/teacher.html.erb

<%= form_for :teacher do |f| %>
  <%= f.text_field :name %> 
  <%= f.submit %>

<% end %> I am new to ruby on rails, so plz help me to solve this problem.I hope u all. plz reply me

bundle exec rake jobs:work

I am newbie to Ruby on Rails development

Can someone please give explain to me what this command line do bundle exec rake jobs:work

I don't understand what is worker and what the command line can do.

Can someone gives me some examples.

Thank you

How to call and Handle request third party API in Ruby on Rails 2.3.5

I want to use third party API and want to make a put and post request and get the response from API in my Rails Application

Ruby and Rails Version of My Application is Below -

Current Version of Ruby -1.8.7 and Rails 2.3.5

May I know which Gem should I have to use?

Thanks in Advance.

mercredi 2 août 2017

private_pub not realtime on production(staging)

i have my app using private_pub for realtime chat.

it works perfectly on local host. but when it is deployed, the chat worked but not realtime.

here is my config/private_pub.yml

development:
  server: "http://localhost:9292/faye"
  secret_token: "secret"
test:
  server: "http://localhost:9292/faye"
  secret_token: "secret"
staging:
  server: "http://ift.tt/2v0uCql"
  secret_token: "1d2ac92b1742d58417ae0a005245e603bab150e34721178c3551079aaf44791d76a1238be7cf54a72d623324ae6612e9f553c5615fdc6dbe84558c1b860b84f8"

i read that i must configure the Faye setting that can run on server. but i dont know how to set it.

pls anyone help me