jeudi 30 juin 2016

ROR uninitialized constant ContatosController::Contato

I am starting to develop in ROR. The user history that I am doing now is a Contact Page. The codes for the MVC are listed below:

app/controller/contatos_controller.rb

class ContatosController < ApplicationController

  def new
    @contato = Contato.new
  end

  def create
    @contato = Contato.new(secure_params)
    if @contato.valid?
      flash[:notice] = "Mensagem enviada de #{@contato.name}."
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def secure_params
    params.require(:contato).permit(:name, :subject, :email, :content)
  end

end

app/models/Contato.rb

class Contato
  include ActiveModel::Model
  attr_accessor :name, :string
  attr_accessor :subject, :string
  attr_accessor :email, :string
  attr_accessor :content, :string

  validates_presence_of :name
  validates_presence_of :subject
  validates_presence_of :email
  validates_presence_of :content
  validates_format_of :email,
    with: /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i
  validates_length_of :content, :maximum => 500

end

app/views/contatos/new.html.erb

<h3>Contato</h3>
<div class="form">
<%= simple_form_for @contato do |form| %>
<%= form.error_notification %>
<%= form.input :name, autofocus: true %>
<%= form.input :subject %>
<%= form.input :email %>
<%= form.input :content, as: :text %>
<%= form.button :submit, 'Submit', class: 'submit' %>
<% end %>
</div>

config/routes.rb

Rails.application.routes.draw do
  resources :contatos, only: [:new, :create]
  root 'static_pages#home'
end

When I try to access http://localhost:3000/contatos/new, the following error is displayed:

NameError in ContatosController#new
uninitialized constant ContatosController::Contato
app/controllers/contatos_controller.rb:4:in `new'

What I found about this error is that it is related to typos, but this does not seem to be my case. It's probably a silly mistake, but I could not find it. Can anybody help me?

Set json attribute to nil within a jbuilder block

I have a scenario where I want to set a json attribute to nil if its object value is nil within a jbuilder block:

example of how I'm doing it now: unless obj.details.nil? json.details do |json| json.value1 obj.details.value1 json.value2 obj.details.value2 end else json.details nil end My question is is there a cleaner way to do this so I don't have to use an unless/else

rbenv/foreman Permission denied @ rb_sysopen - /etc/init/app.conf (Errno::EACCES)

Someone knows how to give rbenv permission to rbenv/foreman export? thank's

[foreman export] writing: app.conf /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/foreman-0.82.0/lib/foreman/export/base.rb:162:in initialize': Permission denied @ rb_sysopen - /etc/init/app.conf (Errno::EACCES) from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/foreman-0.82.0/lib/foreman/export/base.rb:162:inopen' from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/foreman-0.82.0/lib/foreman/export/base.rb:162:in write_file' from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/foreman-0.82.0/lib/foreman/export/base.rb:139:inwrite_template' from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/foreman-0.82.0/lib/foreman/export/upstart.rb:12:in export' from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/foreman-0.82.0/lib/foreman/cli.rb:61:inexport' from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/thor-0.19.1/lib/thor/command.rb:27:in run' from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/thor-0.19.1/lib/thor/invocation.rb:126:ininvoke_command' from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/thor-0.19.1/lib/thor.rb:359:in dispatch' from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/thor-0.19.1/lib/thor/base.rb:440:instart' from /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/foreman-0.82.0/bin/foreman:7:in <top (required)>' from /home/ubuntu/.rbenv/versions/2.2.2/bin/foreman:23:inload' from /home/ubuntu/.rbenv/versions/2.2.2/bin/foreman:23:in `'

group by and filter in rails

I have a model Article in mydb

+----+------------------------+
| id | keywords               |
+----+------------------------+
| 83 | automotive, pet, heath |
| 82 | car, plane             |
| 81 | NULL                   |
| 80 | pet, car               |
| 78 | Null                   |
+----+------------------------+

I want t get result same as:

{
"automotive" => [82], 
"pet" => [82,80], 
"heath" => [83], 
"plane" => [82], 
"car" => "80" 
}

how do i get result same as data above??

How to determine if sum of any given consecutive array elements is equal to a given number in ruby?

I am attempting a coding problem which asks me to print "YES" if the sum of any consecutive array numbers is equal to the given number. The link to the challenge is here

http://ift.tt/29eXjJ7

my solution is here

b = Array.new
a = Array.new
t = gets.to_i
if t >= 0 && t <= 10
    t.times do
         n, x = gets.chomp.split.map(&:to_i)
         n.times do
         a << gets.to_i
         end
         (1..a.length).each do |num|
           a.each_cons(num).each do |pair|
            if  pair.inject(:+) == x
             b << "YES"
            else
             b << "NO"
            end
           end
         end
         if b.include?("YES")
             puts "YES"
        else
             puts "NO"
        end
     end
  end

Although they have accepted my answer, it does not pass all the test cases, hence I am not satisfied.Can someone help me with a correct, more efficient and elegant solution?

Rails: Could not find 'nokogiri' on Windows

I have recently tried to download the 'Nokogiri' gem in rails (on Windows 10 OS) with the following command.

gem install nokogiri

And I received the following error.

ERROR:  While executing gem ... (Errno::EACCES)
Permission denied @ rb_sysopen - C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.8-x86-mingw32/lib/nokogiri/2.2/nokogiri.so

Then when the installation was unsuccessful I tried inserting the following line into my Gemfile

gem 'nokogiri', '~> 1.6', '>= 1.6.6.2' 

This was also unsuccessful

however even after I have removed gem 'nokogiri', '~> 1.6', '>= 1.6.6.2' from the Gemfile I still receive the same error?

After receiving this error I also have not been able to do anything else in rails eg: now when I try to start a new rails project I get the following error

    C:\Sites>rails new app
    C:/RailsInstaller/Ruby2.2.0/lib/ruby/site_ruby/2.2.0/rubygems/dependency.rb:308:in `to_specs': Could not find 'nokogiri' (>= 1.5.9) among 200 total gem(s) (Gem::MissingSpecError)
...

running bundle gives me the following error

   Errno::EACCES: Permission denied @ rb_sysopen - C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.8-x86-mingw32/lib/nokogiri/2.2/nokogiri.so

...

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

I have tried using

 gem install nokogiri --prerelease

I have tried

gem uninstall nokogiri

I have also tried

-Source "http://ift.tt/294AzKV"

How do I fix this issue or revert back to rails before I had these issues?

I have looked everywhere and I can't find an effective solution to this. If there is any more information you require about this please ask in the comments and I'll do my best to give an informative answer.

Thanks

Pluck hash in rails

Is there pluck for a hash?

I have a hash like below and I tried to pluck with following command. I know that it can be done in different ways. But I dunno if there's a pluck method with the following.

hash = {"0"=>{"user_id"=>"1"}, "0"=>{"user_id"=>"2"}}
hash.pluck("user_id")

mercredi 29 juin 2016

Move all nil dependent value using ActiveRecord

I have two model Student and Information. Is this a order by nil?

Student | Information
Leo     | nil
Paul    | Some info1
Peter   | Some info2
Rex     | nil

How can I order it using active record and will show this result:

Student | Information
Paul    | Some info1
Peter   | Some info2
Rex     | nil
Leo     | nil

All nil Student.information.nil? will move down using ActiveRecord.

Using postgres ENUM with rails yields `PG::DatatypeMismatch`

Trying to update the value of a Postgres ENUM column throws the following exception:

ActiveRecord::StatementInvalid Exception: PG::DatatypeMismatch: ERROR: column "interesting_column" is of type interesting_thing but expression is of type integer

LINE 1: UPDATE "interesting_table" SET "interesting_column" = 0, "updated_a...

HINT: You will need to rewrite or cast the expression.

InterestingTable.first.update_attributes!(normal_column: 'food')
  # => perfectly fine
InterestingTable.first.update_attributes!(interesting_column: 'foo')
  # => above exception

Here is the migration to create the table:

class CreateInterestingTables < ActiveRecord::Migration
  def up
    execute <<-SQL
      CREATE TYPE normal_thing AS ENUM ('food', 'water', 'shelter');
      CREATE TYPE interesting_thing AS ENUM ('foo', 'bar', 'baz');
    SQL

    create_table :interesting_tables do |t|
      t.column :normal_column, :normal_thing
      t.column :interesting_column, :interesting_thing
    end
  end

  def down
    drop_table :interesting_tables
    execute 'DROP TYPE normal_thing'
    execute 'DROP TYPE interesting_thing'
  end
end

how can i do images download through polymorphic connection with refile gem on rails 3?

i have images table with images_type - string

here s model of it:

class Image < ActiveRecord::Base
 belongs_to :imageable, :polymorphic => true
end

which is connected to users

class User < ActiveRecord::Base
 has_many :images, :as => :imageable
 accepts_nested_attributes_for :images

 attachment :profile_image

 attr_accessible :profile_image
...
end

schema.rb:

create_table "images", :force => true do |t|
 t.string   "image_type"
 t.datetime "created_at", :null => false
 t.datetime "updated_at", :null => false
end

atm images can be downloaded by refile gem by default settings of it - in a :profile_image

how can i download it on :image_type field?

Mina Foreman sudo: bundle: command not found

someone is having bundle: command not found issue?

-----> Loading environment
-----> Loading rbenv
-----> Creating a temporary build path
-----> Exporting foreman procfile for 
sudo: bundle: command not found
! ERROR: Deploy failed.
-----> Cleaning up build
Unlinking current
OK

foreman stop mina create current folder

Someone know why the mina can't create the current diretory after add foreman?

-----> Cleaning up old releases (keeping 5) -----> Exporting foreman procfile for bash: line 152: cd: /home/ubuntu/test/current: File or directory not found sudo: bundle: command not found ! ERROR: Deploy failed. -----> Cleaning up build Unlinking current OK Connection to 55.77.221.43 closed.

deploy do
    # Put things that will set up an empty directory into a fully set-up
    # instance of your project.
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'rails:assets_precompile'
    invoke :'deploy:cleanup'
    invoke :'foreman:export'


    to :launch do
      queue "mkdir -p #{deploy_to}/#{current_path}/tmp/"
      queue "touch #{deploy_to}/#{current_path}/tmp/restart.txt"
      invoke 'foreman:restart'
    end

Rails: CarrierWave resize_to_ don't working in rails 3

I use CarrierWave to upload file (image)

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  version :medium do
    process :resize_to_limit => [600, 240]
  end

  version :large do
    process :resize_to_limit => [960, 360]
  end
end

In my model

class Listing < ActiveRecord::Base
  mount_uploader :banner, ImageUploader
end

When i upload a image with original size [1006, 368] after upload i have 3 version of image above (original, banner and medium), but both 3 version same size [1006, 368]. Should 3 version have 3 different size. How do i can fix this?

mardi 28 juin 2016

Metronic Theme with Ruby on Rails: Webpage is not rendered properly

New to rails. All rights to bash me if this is silly or stupid. I have done the following steps but still the local host looks like this: enter image description here

I have done the following: 1) Downloaded Metronic Admin Theme 2) Manually added the required css and js to appropriate folders in my app 3) Made changes to html file to satisfy it to be html.erb 4) Pasted a copy of entire theme to vendor/assets folder of my rails app 5) My application.js file is :

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require bootstrap-sprockets
//= require jquery.turbolinks
//= require_tree .

6)Modified my html to as follows:

 <head>
    <title>Metronic | Blank Page Layout</title>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => 'reload' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload' %>

    <%= csrf_meta_tags %>   
        <meta charset="utf-8" />

        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta content="width=device-width, initial-scale=1" name="viewport" />
        <meta content="" name="description" />
        <meta content="" name="author" />


  <script type="text/javascript" src="http://ift.tt/1jAc4pg"></script>
    <script type="text/javascript" src="http://ift.tt/1yCEpkO"></script>


        <!-- BEGIN GLOBAL MANDATORY STYLES -->
        <link href="http://ift.tt/1gelRyP" rel="stylesheet" type="text/css" />
        <link href="/assets/stylesheets/font-awesome.min.css" rel="stylesheet" type="text/css" />
        <link href="/assets/stylesheets/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
        <link href="/assets/stylesheets/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <link href="/assets/stylesheets/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />

7) My application.css.scss is as follows:

@import "bootstrap-sprockets";
@import "bootstrap";


/*
 * This is a manifest file that'll automatically include all the     stylesheets available in this directory
 * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
 * the top of the compiled file, but it's generally better to create a new file per style scope.

*= require bootstrap
*= require_tree 
*= require_self

The actual page should ideally look like this:enter image description here

I use ruby 2.3.0 and rails 4.2.6 All help appreciated.

Query model for all possible values of a column - Ruby Rails [duplicate]

This question already has an answer here:

So I'm learning programming in general, and Ruby specifically; in the course we are developing an app like rottentomatoes.

I need to query the model from the controller, to render in the view the distinct values in that specific column.

I have this piece of haml to embed the result on the template:

  = form_tag movies_path, :method => :get do
    Include:
    - @all_ratings.each do |rating|
      = rating
      = check_box_tag "ratings[#{rating}]"
    = submit_tag 'Refresh'

I have @all_ratings in the controller, I have tried movie[attr_rating] , Movie(:rating)... And I don't know what else to throw to it.

I do not want to hardcode the values (['G','PG','PG-13','R']) in the controller, but learn how to query the model.

why .times is being difficult - Ruby

Can someone please explain to me why the Ruby function .times is being difficult

str.chars.map{|letter| num.times{letter.next}}

is producing just the number (num) for however many letters were in the word instead of moving each letter down the alphabet (.next) that many times. I know it seems simple but from what i understand of .times this is the way to use it but something like this has happened many.times....that was a joke.

Having a module class with the same name as a top level class: 'expected module_classe_file to define top_level class'

My apps/model folder looks like that:

models/
  module/
    category.rb
  category.rb

But I can't seem to find a way to correctly autoload module/category: I always have the error Expected /app/models/module/category.rb to define Category.

As of now I only see two options: not adding it to autoloading, or renaming module/category.rb to module/module_category.rb, neither seems like a good idea

debian capistrano 3 default PATH environment variable

I dont know why but during

cap production deploy 

echo $PATH prints

/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games

instead off

PATH=/usr/local/rvm/gems/ruby-2.3.0/bin:/usr/local/rvm/gems/ruby-2.3.0@global/bin:/usr/local/rvm/rubies/ruby-2.3.0/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/usr/local/rvm/bin

My deploy.rb

# config valid only for current version of Capistrano
lock '3.5.0'

set :application, 'app'
set :branch, "master"
set :repo_url, 'git@github.com:url/repo.git'
set :deploy_to, "/home/deploy/app"
set :unicorn_conf, "#{deploy_to}/current/config/unicorn.rb"
set :unicorn_pid, "#{deploy_to}/shared/pids/unicorn.pid"

set :linked_files, %w{config/database.yml}
set :linked_dirs, %w{bin log pids system tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads}

namespace :deploy do
   task :restart do
   on roles :all do
   execute "echo $PATH; if [ -f '/home/deploy/app/shared/pids/unicorn.pid' ] && [ -e /proc/$(cat '/home/deploy/app/shared/pids/unicorn.pid') ]; then kill -9 `cat /home/deploy/app/shared/pids/unicorn.pid`; cd /home/deploy/app/current &&  bundle exec unicorn_rails -E production -c config/unicorn.rb -D; else cd /home/deploy/app/current && bundle exec unicorn_rails -E production -c config/unicorn.rb -D; fi"
end
end
    after :publishing, :restart
end

And as i have default PATH variable during deploy bundle cant find unicorn_rails, althouth it is installed.

Add Methods to Iterated Objects

I have a block that looks similar to this one:

    <% @github_tmp_files.files.each do |file| %>
      <li><%= link_to @github_tmp_files.filename(file.key), @github_tmp_files.download_url(file.key) %></li>
    <% end %>

As you can see in the loop I call two methods with file as the argument:

@github_tmp_files.filename(file.key)
@github_tmp_files.download_url(file.key)

I would prefer to call this two methods like that:

file.filename (should return) @github_tmp_files.filename(file.key)
file.download_url (should return) @github_tmp_files.download_url(file.key)

So that at the end I can write the loop like this:

     <% @github_tmp_files.files.each do |file| %>
      <li><%= link_to file.filename, file.download_url %></li>
    <% end %>

How do I have to change the files method in @github_tmp_files, so that it allows this behaviour? Thanks

#in @github_tmp_files -> Class

def files
   github_bucket.objects(prefix: @folder)
end

Raw pg GROUP BY query in rails application

I have this very simple SQL query that i am trying to execute in my rails console.

SELECT name, manual_score FROM objectives GROUP BY manual_score

But it throws an error which is:

ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "objectives.name" must appear in the GROUP BY clause or be used in an aggregate function

I have tried by prepending table name with columns but the error remains. Any help would be appericiated. Thanks!

ActionView::Template::Error (Failed to open TCP connection to localhost:9292 (Connection refused - connect(2) for "localhost" port 9292))

Please give me some solution for the following error.

This is a chat application.... and the code and error is as follows::

conversations_controller.rb

def create
    if Conversation.between(params[:sender_id],params[:recipient_id]).present?
      @conversation = Conversation.between(params[:sender_id],params[:recipient_id]).first
    else
      @conversation = Conversation.create!(conversation_params)
    end
    render json: { conversation_id: @conversation.id }
  end

Create.js.erb

<% publish_to @path do %>
        alert(@path);       
    var id = "<%= @conversation.id %>";
    var chatbox = $("#chatbox_" + id + " .chatboxcontent");
    var sender_id = "<%= @message.user.id %>";
    var reciever_id = $('meta[name=user-id]').attr("content");

    chatbox.append("<%= j render( partial: @message ) %>");
    chatbox.scrollTop(chatbox[0].scrollHeight);

    if (sender_id != reciever_id) {
        chatBox.chatWith(id);
        chatbox.children().last().removeClass("self").addClass("other");
        chatbox.scrollTop(chatbox[0].scrollHeight);
        chatBox.notify();
    }
<% end %>

Error shown on Console:

ActionView::Template::Error (Failed to open TCP connection to localhost:9292 (Connection refused - connect(2) for "localhost" port 9292)):
    1: <% publish_to @path do %>
    2:      alert(@path);       
    3:     var id = "<%= @conversation.id %>";
    4:     var chatbox = $("#chatbox_" + id + " .chatboxcontent");
  app/views/messages/create.js.erb:1:in `_app_views_messages_create_js_erb___1855030059461646481_70563200'

Please give some solution for this issue.

Thanks in advance.

Associated Scopes not working until I made any change in register file

I have to models restaurant and cuisine with many to many association. And I have this in my app/admin/restaurant.rb

ActiveAdmin.register Restaurant do
  scope("All"){|scope| scope.order("created_at desc")}
  Cuisine.all.each do |c|
    scope(c.name) { |scope| scope.joins(:cuisines).where("cuisines.id=?",c.id)}
  end
end

The problem is whenever I delete or add a new cuisine the scopes do not change until I made any change in my admin/restaurant.rb file. How can I fix this issue

lundi 27 juin 2016

Getting error on aws

I have setup my project on aws server .Now I am doing bundle install and I am getting this error.

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /usr/local/rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20160628-9837-1r9tsw1.rb extconf.rb
checking for ruby/thread.h... yes
checking for rb_thread_call_without_gvl() in ruby/thread.h... yes
checking for rb_thread_blocking_region()... no
checking for rb_wait_for_single_fd()... yes
checking for rb_hash_dup()... yes
checking for rb_intern3()... yes
checking for mysql_query() in -lmysqlclient... yes
checking for mysql.h... no
checking for mysql/mysql.h... yes
checking for errmsg.h... no
-----
errmsg.h is missing. You may need to 'apt-get install libmysqlclient-dev' or 'yum install mysql-devel', and try again.
-----
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/local/rvm/rubies/ruby-2.2.1/bin/$(RUBY_BASE_NAME)
    --with-mysql-dir
    --without-mysql-dir
    --with-mysql-include
    --without-mysql-include=${mysql-dir}/include
    --with-mysql-lib
    --without-mysql-lib=${mysql-dir}/lib
    --with-mysql-config
    --without-mysql-config
    --with-mysql-dir
    --without-mysql-dir
    --with-mysql-include
    --without-mysql-include=${mysql-dir}/include
    --with-mysql-lib
    --without-mysql-lib=${mysql-dir}/lib
    --with-mysqlclientlib
    --without-mysqlclientlib

extconf failed, exit code 1

Gem files will remain installed in /usr/local/rvm/gems/ruby-2.2.1/gems/mysql2-0.3.21 for inspection.
Results logged to /usr/local/rvm/gems/ruby-2.2.1/extensions/x86_64-linux/2.2.0/mysql2-0.3.21/gem_make.out
Using raindrops 0.16.0
Using sass 3.4.22
Using tilt 2.0.5
Using spring 1.7.1
Using sqlite3 1.3.11
Using will_paginate 3.1.0
Using rdoc 4.2.2
Using tzinfo 1.2.2
Using nokogiri 1.6.8
Using rack-test 0.6.3
Using warden 1.2.6
Using mime-types 3.1
Using net-scp 1.2.1
Using binding_of_caller 0.7.2
Using sprockets 3.6.0
Using coffee-script 2.4.1
Using uglifier 3.0.0
Using httparty 0.13.7
An error occurred while installing mysql2 (0.3.21), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.3.21'` succeeds before bundling.<br/>

I did gem install mysql2 -v '0.3.21' OR yum install mysql-devel both did not work for me .Can anyone tell me what can be the possible problem

Code analysis using the ruby gem

I want to do the code analysis by using the ruby gem.I installed the ruby gem from http://ift.tt/293N6gs i am unable to do the code analysis with this.I don't know exact procedure.Can any one tried on it.If yes please share your opinions on this question.

Error While creating a new Rails Project in Rails 5.0.0.rc1

I am trying to create a new Rails project- in fact, it is chapter 3 of Michael Hartl RubyonRails. Anytime I try to create the sample_app I get this message :

$ rails 5.0.0.rc1 new sample_app
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/dependency.rb:319:in to_specs': Could not find 'railties' (= 5.0.0.rc1) - did find: [railties-4.2.2] (Gem::LoadError) Checked in 'GEM_PATH=/usr/local/rvm/gems/ruby-2.3.0:/usr/local/rvm/gems/ruby-2.3.0@global', executegem env` for more information

It looks like for some reason it is not adding the new app gems. I am a total newbie, so I appreciate any input in trying to figure this stuff out !

Thanks a lot !

J

Why is my controller acting different in the rspec execution than in the browser execution?

I have my controller:

class Api::BunknotesController < Api::ApiController
  # ... omitted code
  def show
    @bunknote =
      current_user.bunknotes.includes(:person).find(params[:id])

    respond_to do |format|
      format.html {
        render layout: false
      }
      format.pdf {
        render pdf: @bunknote.filename,
          template: '/bunknotes/show.pdf',
          margin: { top: 5, bottom: 5 }
        byebug
      }
      format.json {
        render json: @bunknote.api_json(true)
      }
    end
  end
  # ... omitted code
end

In the second format, Wicked PDF is used to render. The rendered template looks like this:

<%= wicked_pdf_stylesheet_link_tag "bunknotes" %>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<div class="page <% if @bunknote.reply %>pagebreak<% end %> bunknote_pdf">
    <div class="bn-id">bn<%= @bunknote.id %></div>
    <h1>Bunk Note to <%= @bunknote.person ? @bunknote.person.name : @bunknote.writein %> <%= "(#{@bunknote.address})" if @bunknote.address && @bunknote.address.length > 1 %></h1>
    <%= render partial: 'details', locals: { :bunknote => @bunknote } %>
</div>
<% if @bunknote.reply %>
<div class="page bunkreply-stationery">
  <%=
    render partial: '/common/stationery',
    locals: {
      user_fullname: @bunknote.user.fullname,
      org_name: @bunknote.organization.name,
      org_id: @bunknote.organization.id,
      user_id: @bunknote.user.id,
      bunknote_id: "bn#{@bunknote.id}",
      barcode_value: "#{has_bunknote = 1}#{@bunknote.id}",
      height: "720px",
      camper_name:  @bunknote.person ? @bunknote.person.name : @bunknote.writein
    }
  %>
</div>
<% end %>

When I try to hit my controller, I have a template error. The error's nature is like this: Inside my show.pdf.erb template, which is /bunknotes/show.pdf.erb, I am referencing the file 'details'. Since my controller is Api::BunknotesController (there is another controller named BunknotesController, without prefix, which had a copy of this template in first place), the relative inclusion would try to find the file in /app/views/api/bunknotes/ instead of /app/views/bunknotes.

By trying to hit it in my browser, I get a 500 when trying to render the pdf, and the byebug instruction is not reached (as anyone could expect when having any exception out of the special purpose ones in rails like RecordInvalid and so). Due to other internals, the generated pdf is corrupt on this scenario (something we will fix later but for now it serves as a good sign that something did not go well).

However a pretty different behavior is triggered when running a test

My test file looks like:

# ... omitted code
describe Api::BunknotesController do
    # ... omitted code
    it "gets a bunknote (PDF)" do
      get :show, {id: bunknote1.id, format: :pdf}
      expect(response.status).to be 200
    end
    # ... omitted code
end
# ... omitted code

When the rspec utility runs this example, A blank pdf (non-corrupt, but totally blank) is generated by the controller, and a 200 response code is returned.

I made this test to succeed for a 200 code if things got well. The test should have failed when the show view misreferenced (for my needs) the inner view. But instead it succeeded, seeming to absorb the error like a diaper, and generating the blank PDF file. I expect that this behave exactly as the browser call, generate the corrupt pdf, returns a 500 code, and fails.

Summary:

  1. Yes, I will fix the path to the included view so it is absolute.
  2. Yes, I will fix the corrupt pdf generation so that no pdf attachment files are ever sent.
  3. The test should not have succeeded as it did. The test is expected to succeed only if the response code is 200. This is right, but the controller produced a 200 in the rspec execution, while returning a 500 in the browser execution.

Why is my controller acting different in the rspec execution than in the browser execution?

I am using:

  • Ruby 2.3.0p0
  • Rails 3.2.22.2
  • RSpec 3.4.1

Rails 3 Nested Model Form with Javascript

I have created a nested model form for Lessons to Questions and Answers. It was not picking up the coffee script so I have add it the coffee code as Javascript but i am get an error and Add Question is not working. Anyone and assist please.

Lesson.rb

has_many :questions
accepts_nested_attributes_for :questions, :allow_destroy => true

Question.rb

belongs_to :lesson
has_many :answers
accepts_nested_attributes_for :answers, :allow_destroy => true

Answer.rb

belongs_to :question

application_helper.rb

def link_to_add_fields(name, f, association) new_object = f.object.send(association).klass.new
    id = new_object.object_id
   fields = f.fields_for(association, new_object, :child_index => id) do   |builder|
  render(association.to_s.singularize + "_fields", :f => builder)
end
link_to(name, '#', :class => "add_fields", :data => {:id => id, :fields =>   fields.gsub("\n", "")}) end

admin/lessons/_form.html.erb

 <%= form_for([:admin,@lesson]) do |f| %>
          <% if @lesson.errors.any? %>
            <div class="notification error png_bg">
                <a href="#" class="close"><img src="/assets/admin/icons/cross_grey_small.png" title="Close this notification" alt="close" /></a>
                <div>
                <h2><%= pluralize(@lesson.errors.count, "error") %></h2>

                  <ul>
                  <% @lesson.errors.full_messages.each do |msg| %>
                    <li><%= msg %></li>
                  <% end %>
                  </ul>
                </div>                          
            </div>
          <% end %>

  <label class="formlabel">Lesson Title</label>
  <%= f.text_field :title  %>

 <%= f.fields_for :questions do |builder| %>
 <%= render 'question_fields', :f => builder %>
 <% end %>
 <%= link_to_add_fields "Add Question", f, :questions %>

 <%= f.submit 'Save', :class => 'button' %>

_question_fields.html.erb

 <fieldset>
    <%= f.label :content, "Question" %><br />
    <%= f.text_area :content %><br />
    <%= f.check_box :_destroy %>
    <%= f.label :_destroy, "Remove Question" %>
    <%= f.fields_for :answers do |builder| %>
       <%= render 'answer_fields', :f => builder %>
    <% end %>
    <%= link_to_add_fields "Add Answer", f, :answers %>
 </fieldset>

_answer_fields.html.erb

 <fieldset>
    <%= f.label :content, "Answer" %>
    <%= f.text_field :content %>
    <%= f.check_box :_destroy %>
    <%= f.label :_destroy, "Remove Answer" %>
 </fieldset>

Here is the javascript I have added just before the end of the the head tag. I am getting an error of "$('form').on is not a function. (In '$('form').on', '$('form'....

<script>
            jQuery(function() {
              $('form').on('click', '.remove_fields', function(event) {
                $(this).prev('input[type=hidden]').val('1');
                $(this).closest('fieldset').hide();
                return event.preventDefault();
              });
              return $('form').on('click', '.add_fields', function(event) {
                var regexp, time;
                time = new Date().getTime();
                regexp = new RegExp($(this).data('id'), 'g');
                $(this).before($(this).data('fields').replace(regexp, time));
                return event.preventDefault();
              });
            });
        </script>

Override javascript_tag type for json-ld in Rails 3.2.x

Looking at the underlying code for javascript_tag it may not be possible, but does anyone know if it's possible to override the javascript_tag default type of type="text/javascript" in Rails 3.2.2? Or possible without a lot of janky code?

I'm trying to do something like this, but I can look into other options.

javascript_tag type: 'application/ld+json' do
    some stuff here
end

Rails application to not redirect to HTTPS on specific controller and action

How can my application not redirect to HTTPS on a certain controller and action ? In my case it's the controller transaction and action update_payment. I'm having loop redirect problem on production.

I've tried using the the gem rack-ssl-enforcer and putting the following in the production.rb:

config.middleware.use Rack::SslEnforcer, :except => [%r{update_payment$}], :strict => true

Still, it seems it's not working..

How to skip the malformated & invalid utf-8 errors.When csv file uploading in ralis app?

I have handle more-then 5lks data.I have working with CSV & XLSX formats. When i uploading a CSV file i have ('Rails Import CSV Error: invalid byte sequence in UTF-8' and 'Malformed error') and-then i uploading a Xlsx file i have ('Roo spreadsheet uploading OLE2 signature is invalid'). Please someone help me? This my view page code...

<%=form_for[@product],:url{:controller=>"products",:action=>"import_process"} do |f| %>

  <%= f.file_field :file1,:accept=>".csv"%>

   <button type="submit" class="btn btn-info" onclick="return ValidateExtension()" data-qslid="l2"><i class="fa fa-cloud-upload"></i>Upload</button><br/><br/>

    <%end%>

dimanche 26 juin 2016

How to skip the malformation & utf-8 errors.When file uploading in ralis app?

I have handle more-then 5lks data so i cannot check cell by cell. I have working with CSV & XLSX formats.Please someone help me?This my view page code...

<%=form_for[@product],:url{:controller=>"products",:action=>"import_process"} do |f| %>

  <%= f.file_field :file1,:accept=>".csv"%>

   <button type="submit" class="btn btn-info" onclick="return ValidateExtension()" data-qslid="l2"><i class="fa fa-cloud-upload"></i>Upload</button><br/><br/>

    <%end%>

Rails jQuery.scrollTo file not found after gem has been installed

I made a simple html website with some jQuery effects that I am now trying to create a rails app out of. In the original version I just copied jquery's scrollto library into a text document and linked to it in the header. From what I understand in rails it would be cleaner to just install it as a gem following these instructions http://ift.tt/292D3dy. I followed them exactly as shown, but when I run my site on localserver I see this error message

Sprockets::FileNotFound in Welcome#index

Showing /home/connor/Port/app/views/layouts/application.html.erb where line #6 raised:

couldn't find file 'jquery.scrollTo' with type 'application/javascript'

Extracted source (around line #18):

18

//= require jquery.scrollTo

The rest of my jquery effects are running fine, changing classes on click etc...

Rails edit migration file to include index?

I've just been trying to figure out some ways to optimize my MySQL database, but I'm having a bit of an issue with indexing here.

As opposed to stacking up a bunch of migration files (since I'm not really managing much data yet), I'm simply "going back" and editing migration files periodically to include columns, etc. Not sure if this is best practice, but I figured it'd be easier to avoid ending up with 100 migration files adding small things.

Anyways, I'm trying to add an index to one of the columns in a migration file, but I can't seem to get it to work (it's not showing up in the schema file after rolling back and migrating again).

class CreateVuln < ActiveRecord::Migration
  def change
    create_table :vuln do |t|
      t.integer :node_id
      t.string :node_identifier
      t.string :vuln_finding_identifier

      t.timestamps null: false
    end

    add_index :vuln, :node_identifier
  end
end

But when I go to schema.rb, here's what it looks like:

  create_table "vuln", force: :cascade do |t|
    t.integer  "node_id",                 limit: 4
    t.string   "node_identifier",         limit: 255
    t.string   "vuln_finding_identifier", limit: 255
    t.datetime "created_at",                               null: false
    t.datetime "updated_at",                               null: false
  end

Can someone tell me what I'm missing here? If I add a new migration by running rails g migration AddIndexToVuln node_identifier:string:index then I can see that the schema.rb file gets updated properly. schema.rb then adds this line: add_index "vuln", ["node_identifier"], name: "index_vuln_on_node_identifier", using: :btree

So as opposed to creating a new migration file, I'm just wondering if I can just roll back my database and make the changes in the existing migration file for that table.

samedi 25 juin 2016

Rails Admin Sort By Relation Attribute

I got a rather old app using Rails Admin 0.4. I am not a guy so much good with magic and thus would need some help with Rails Admin configuration.

I am in need of sorting the list view of a model by a relation attribute. For example I got a setup like Exchange belongs_to :worker, :class_name => "Person", :foreign_key => "worker_id". I would like to sort it by the name attribute of the Person.

A bare installation sorts it by the #id of the person (worker_id in this case). I would like that to be #name in the Person class.

Stuff are as follows, though I doubt will be necessary to help.

RailsAdmin.config do |config|
  config.model ExchangeAndFee do
    list do
      field :created_at
      field :customer do
        searchable [{Person => :name}]
        queryable true
      end
      field :worker do
        searchable :workers_exchanges => :name
        queryable true
      end
      field :amount
      field :notes do
        label "Memo"
        formatted_value do
          bindings[:object].memo
        end
      end
    end
  end
end

enter image description here

Additional Details

  • Rails 3
  • Rails Admin 0.4
  • App OSCurrency

Any help is highly appreciated.

vendredi 24 juin 2016

How do you display images onto a canvas using Ruby's Carrierwave gem and Fabric.js?

First, I am a newbie and your help is much appreicated.

Hi, I am using the Ruby Carrierwave gem and Fabric.js in my canvas app. I use CarrierWave to assist on storing my images in the database and I use Ruby's .each iterator to display the images on the page(see below). It works great.

<canvas id="canvas" width="300" height="550"></canvas>
 <% @images.each do |m| %>
  <%= image_tag m.photo_pic.url, :class => "my-image",  %>
 <% end %>

I then use a fabric.js javascript function to display the images in my canvas.(see below) It works However no matter what image I click it always displays the first image into the canvas. I would like to click the 10th image for example and the 10th image to display on my canvas. Is this possible?

var canvas = new fabric.Canvas('canvas');
 $(".my-image").on('click',function() {
  var imgElement = document.getElementsByClassName("my-image")
  var imgInstance = new fabric.Image(imgElement, {
   left: 50,
   top: 50,
 });
 canvas.add(imgInstance);
 });

Thanks again for your help. I might need a different title but I think this could really help others out who are using Ruby and Fabric.js in there projects. Best

Passenger 5.0.28 gets error trying to start Rails 3.2 application

I'm getting the following error attempting to access a new deployment of an old Rails 3.2 application:

An error occurred while starting up the preloader.
It sent an unknown response type "socket: 
http://unix:/tmp/passenger.gChlXdF/apps.s/preloader.1q3kca0\n".

I saw a similar question and answer on SO, but my situation is different. My config.ru file is as follows:

require ::File.expand_path('../config/environment',  __FILE__)
run MyApp::Application

So, not doing any STDOUT redirects there. It looks like Passenger is giving itself a bad time by the looks of the error. Not sure where to begin.

SimpleCov Not Giving Code Coverage for Watir-Rails Actions

Using Rails 3, SimpleCov (0.9.2) gives me code coverage for all of my tests but fails to give me a report on what my automated Watir-Rails (1.2.1) browser calls in an ActionDispatch::IntegrationTest. Code that is called normally (ie not through Watir) shows up on the coverage fine. I've tried to configure my files like one would with the Selenium webdriver since I've heard that Watir is built on top of that, but that isn't doing the trick. Is there some extra setup I have to do in order to make it all work together?

Rails Model association with tabless Model

I want to perform has_one, belongs_to association on a tableless model.

class A < ActiveRecord::Base
  has_one: b
end

class B < Tableless
   attr_accessor: b
end

I want to know whether this is possible in Rails

Rails Model association with tabless Model

I want to perform has_one, belongs_to association on a tableless model.

class A < ActiveRecord::Base
  has_one: b
end

class B < Tableless
   attr_accessor: b
end

I want to know whether this is possible in Rails

Rails Model association with tabless Model

I want to perform has_one, belongs_to association on a tableless model.

class A < ActiveRecord::Base
  has_one: b
end

class B < Tableless
   attr_accessor: b
end

I want to know whether this is possible in Rails

Architecture of a write intensive feature

I use Ruby on rails backed by oracle database and memcached for my current project.

There is a pretty heavy used feature, which relies on a single database views as a datasource, and this data source internally has other database views and tables inside.

It's a virtual db view, to be able to access everything from one place, not a materialized db view.

Users most of the times if they are in the feature they are looking to update, so having data up to date is important.

When obtaining data from this view, I inner join security table to the view (security table is not part of the view itself) which contains some fields that we use to control data access on more granular level. For example security table has user_id, prop_1, prop_2 columns, where prop_1, prop_2 are columns available on a db view and the user_id is a logged in user. Some users have same props in the security table say prop_1 = 1 and prop_2 = 1, but also can have prop_1 like the other user but have different prop_2 like prop_1 = 2 and prop_2 = 1. There are many different combination of prop_1 and prop_2, think about them as a FK to another table, so possible to have many entries.

By now the time to retrieve the records on the app is almost 10 seconds, it's pretty slow. I m considering alternative approach.

First thing I though of was the materialized view, but since the user do frequent updates, it might not be the best choice, as refreshing the view might take time.

Second thing I thought about was the cache, to use prop_1 and prop_2 combination as a composite key to the underlying data, as many users have the same combination and whoever has the same combination can access the same data.

However this approach might require more code rewrites and logic to save and retrieve data in fragments, rather from one location with one query like in the database view.

In your experience, how did you address same/similar issue? Or is there a better approach that I could try?

For those of you about to ask, what have you tried. I m thinking about the solution first, gathering information from reliable resources and more experienced people, then I m gonna make an informed decision and start implementing. Implementing first, thinking second, proved so wrong so many times

jeudi 23 juin 2016

How to show an associated value from a selected record in Rails 4.0 form

I am fairly new to RoR, currently working on a little free app for amateur sports clubs managers that help them to keep track of payments. This app shows relevant player data and a form to collect fees (tarifa) payments. I want to show the fee for the concept being paid before the payment is entered. This is the app view with the form and the HTML generated: form for pagos

this is the pagos_controller.rb 'new' action:

def new
  @pago = Pago.new
  @conceptos = Concepto.all
  @jugador = Jugador.find_by(id: params[:jugador_id])
end

and this is the views/pagos/_form.html.erb rendered into the views/pagos/new.html.erb :

<%= form_for(@pago) do |f| %>
 <% if @pago.errors.any? %>
  <p> All the error showing logic is omitted here for simplicity </p>
 <div class="field-tm">
   <%= f.label :concepto %>
   <%= f.collection_select :concepto, @conceptos, :name, :name %>
 </div>
 <div class="field-tm">
   <%= f.label :tarifa %> <div id="la-tarifa"> </div>
 </div>
 <div class="field-tm">
   <%= f.text_field :cantidad, :placeholder => "Cantidad a pagar" %>
 </div>
 <%= f.hidden_field :jugador_id, :value => params[:jugador_id] %>
 <div class="actions">
  <%= f.submit "Registrar Pago", class: "btn btn-default"%>
 </div>
<% end %>

This is the pagos schema...

create_table "pagos", force: :cascade do |t|
  t.string   "concepto"
  t.decimal  "cantidad"
  t.integer  "jugador_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

And the Conceptos schema:

create_table "conceptos", force: :cascade do |t|
  t.string   "name"
  t.decimal  "tarifa"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

I need to get the value selected in the 'collection_select' to use it to find that concept's tarifa like in

@conceptos.find_by(name: theConceptoName).tarifa

and put it in the

$("#la-tarifa").text(tarifa)

to show the value, but don't know how to get a 'theConceptoName' variable that works from the

<%= f.collection_select :concepto, @conceptos, :name, :name %>

I've tried several ways and I came up with jQuery way to get the value, so it would be something like this:

$("#pago_concepto").change( function(){
  var miConcepto = $("#pago_concepto").value();
  do the @conceptos search for miConcepto and get the tarifa;(*)
  $("#la-tarifa").text(tarifa);
});

but then how do I do the query(*) within the pagos.cofee code to get the tarifa value from @conceptos... I have done a lot of google research but every answer I find confuses me more. Please help me.

Setting up react JSX in ruby on rails.

I'm trying to learn react and integrate it to Ruby on Rails.

To start with I included the following gem.

gem 'react-rails', '~> 1.0'

Rails app was set up and react integration was also done and working fine.

In my erb page i'm using helper method react_component to render some data.

<%= react_component 'Records', { data: @records } %>

Following is my react JS code react.DOM syntax

@Records = React.createClass
    render: ->
      React.DOM.div
        className: 'records'
        React.DOM.h2
          className: 'title'
          'Records'

Now my aim is to use JSX instead of react.DOM structure.

So i replaced the above code with .

@Records = React.createClass
 render: ->
    `<div className="records">
      <h2 className="title"> Records </h2>
    </div>`

And it gave me the following error.

Uncaught SyntaxError: Unexpected token <.

From my search I understood that this has to do with inclusion of JSX. How can i solve this issue ?

Which extension should i be using? .coffee or .js or .jsx.

Any information regarding this is highly appreciated.

Rails subset of index route

Is it possible to make an (almost) duplicate of the RESTful controller#index route to show a subset of what might show on the index page?

Here's my scenario: I have a network_hosts controller and the index action is showing all network hosts. I'd like to make another route that shows a subset of those network_hosts, say, ones that have a certain validity score (as set by the user).

I thought I was on the right track, but what I've done so far tries to forward to the show action for the controller, so obviously I don't understand what I'm trying to accomplish.

routes.rb

resources :network_hosts
  get 'network_hosts/hosts_risk' => 'network_hosts#hosts_risk', as: :hosts_risk

network_hosts_controller.rb

class NetworkHostsController < ApplicationController

  def index
    @network_hosts = NetworkHost.all
  end

  def hosts_risk
    # only hosts below 99% validity
  end
end

views/network_hosts/ directory tree

 |views/
 |
 |__ network_hosts/
    |
    |__ index.html.erb
    |__ hosts_risk.html.erb

Running bundle exec rake routes shows the path exists:

new_network_host GET  /network_hosts/new(.:format)        network_hosts#new
edit_network_host GET /network_hosts/:id/edit(.:format)   network_hosts#edit
network_host GET      /network_hosts/:id(.:format)        network_hosts#show
             PATCH    /network_hosts/:id(.:format)        network_hosts#update
             PUT      /network_hosts/:id(.:format)        network_hosts#update
             DELETE   /network_hosts/:id(.:format)        network_hosts#destroy
hosts_risk   GET      /network_hosts/hosts_risk(.:format) network_hosts#hosts_risk

So, when I wire up the route with <%= link_to "Hosts at Risk", hosts_risk_path %> I get this error:

ActionView::MissingTemplate (Missing template network_hosts/show, application/show with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}. Searched in:
  * "/Users/godzilla74/Coding/neo-api/app/views"
  * "/Users/godzilla74/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rails_admin_tag_list-0.2.0/app/views"
  * "/Users/godzilla74/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rails_admin-0.8.1/app/views"
  * "/Users/godzilla74/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/kaminari-0.16.3/app/views"
  * "/Users/godzilla74/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.2/app/views"
  * "/Users/godzilla74/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/apipie-rails-0.3.5/app/views"
):

What I have missed or done wrong?

Query from database does not return in rails

My rails app has a User model and a Role model. Each User belongs to one role and each role has many users. There three methods defined in the user model to check the role of that user def admin?, def user?, and def expert?.

The User class:

class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader

  validates_presence_of :name
  validates_presence_of   :avatar
  validates_integrity_of  :avatar
  validates_processing_of :avatar

  before_save :assign_role
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  belongs_to :role
  has_many :items
  belongs_to :organization
  has_many :expertkeywordmodels
  has_many :keywords, through: :expertkeywordmodels

  def assign_role
    self.role = Role.find_by name: "Admin" if self.role.nil?
  end

  def self.with_role(role)
     my_role = Role.find_by_name(role)
     where(:role => my_role)
  end

  def admin?
    self.role.name == "Admin"
  end

  def user?
    self.role.name == "User"
  end

  def expert?
    self.role.name == "Expert"
  end

end

The Role class:

class Role < ActiveRecord::Base
  has_many :users
end

I am trying to create a collection_select only with users that have expert role. Something like:

<%= collection_select(:keyword, :user_ids, User.where('expert?'), :id, :name, {prompt: true}, {:multiple => true}) %>

But it does not recognize expert? as a method. I was wondering if anyone knows how can I perform this query. I am sorry if this is a naive question as I am new to rails.

Thanks, Amir

losing css styles in rails

I generate this scaffold rails generate scaffold Caa::Documents name1: ...... wich has created this scss file app/assets/stylesheets/caa/documents.css.scss

I have local clone (git clone) of production app (rails 3.2.21 ,ruby 1.9.3. p0) where this scss file works perfectly.

but when I have pushed (git) back to production server (rails 4.1.0 , ruby 1.9.3.p0) corresponding views lost scss s from that file. when I press F12 in browser this file is missing from css list.

Im adding this component at already existing big project thats why Im lost . (all new files are from scaffold generate)

I understand that exact answer is hard to find without having access to code but you can give me an advice from where I should start research and what could be a reason ?

thanks

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

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

rvm rubies

   ruby-1.9.3-p551 [ x86_64 ]
   ruby-2.1.5 [ x86_64 ]
   ruby-2.2.4 [ x86_64 ]
 * ruby-2.3.0 [ x86_64 ]
   ruby-2.3.1 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

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

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

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

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

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

Nicer way to provide Date Range

I create a date time range like this in rails:

last_3_months = (Date.today - 3.month)..Date.today
next_40_days = Date.today..(Date.today + 40.days)

Is there a nicer way in Ruby to make it more readable? Something like:

last_3_months = 3.months.ago.to_range
next_40_days = 40.days.from_now.to_range

Thanks a lot!

Ruby on Rails(Form submit)

I have two models User and Business. There is no association between them how can I show attributes of them in one single view with one submit.

mercredi 22 juin 2016

gmaps4rails - map breaks when user country, state, city are optional

My problem is, the user has the option to enter city, state, country. It is not mandatory for the user to enter any. I noticed that when user has entered city only or just the state only, the map breaks (shows the ocean?). I've tried to follow similar problems (not exactly the problem I'm having) but still went through them: (Gmaps4rails: How to set current user location on map by default in Rails 4) and (Fetch all entries exept those with empty column in Rails)

This is what I have so far...

userprofile.rb

geocoded_by :full_address
after_validation :geocode

def full_address
  [city, state_prov, country].compact.join(', ')
end

userprofiles_controller.rb

def index

  @userprofiles  = Userprofile.all
  @location =  @userprofiles.all(:conditions => "country <> ''")

  @hash = Gmaps4rails.build_markers(@location) do |map, marker|
    marker.lat map.latitude
    marker.lng map.longitude
    marker.picture({
                     "url" => view_context.image_path("blue_dot.png"),
                     "width" => 36,
                     "height" => 36,
                 })
  end
end

Currently, the map only works if country is there. But I need the map to work if the country, state_prov and city are all optional. So if the country is missing, but state_prov and city is filled out.. it should be able to display the marker.

Does the geocoder not return by what they can find? For example, if country is missing but state and city is there, it uses that? Any insight would help, thanks!

Adding the data from html.erb file into database

Doing Rails (new to Rails).... and would like to add the fields into the database (which my code is not doing). I have 2 models:

# == Schema Information
#
# Table name: claims
#
#  id         :integer          not null, primary key
#  status     :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Claim < ActiveRecord::Base
    has_many :claim_items
end

and

# == Schema Information
#
# Table name: claim_items
#
#  id         :integer          not null, primary key
#  item_title :string
#  lp_number  :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class ClaimItem < ActiveRecord::Base
    belongs_to :claim
end

ClaimItem is a single item that contains lp_number and item_title. 'Claim' represents a storage for claim_items and has field status.

The problem is a user can select (checkbox) a multiple checkboxes, and after clicking the 'Submit' button, the lp_number and title should be stored in the database after method create gets executed. But I'm pretty sure I did my html.erb file wrong:

<body>
        <%= form_for @claim, :url => { :action => "create" } do |f| %>
            <h3>Please check the items <br></h3>
            <% @lp_title.each do |lp_number, title| %>
                    <%= check_box_tag "check_box", lp_number, checked = false %> 
                    <%= lp_number + ": "%> <%= link_to title, @lp_image[lp_number]%>
                    <br>
                    <%= select_tag(:user_id,    '<option value="0">---Select a reason---</option>
                                                 <option value="1">Bought by mistake</option>
                                                 <option value="2">Missing parts or accessories</option>
                                                 <option value="3">Didn\'t approve purchase</option>'.html_safe)%>

                    <br>
                        <%= text_area :issue_description, :cols => "100", :rows => "100" %>
                    <br>
                    <br>

            <% end %>
            <%= f.submit "Submit" %>
        <% end %>
</body>

Method create

def create 
        @claim = Claim.new(params[:post])
        if @claim.save
            redirect_to :action => 'show'
        else 
            redirect_to :action => 'new'
        end

    end

ActiveRecord::RecordNotFound in ChargesController#create

I have an app with a user model, pin model, and charges controller for stripe payments. I get the following error when I login in as a user in development and try to purchase a pin via stripe payments:

ActiveRecord::RecordNotFound in ChargesController#create

Couldn't find Pin without an ID

It indicates that the error is coming from @pin = Pin.find(params[:id]) from the code below. I believe it is doing this because the pin is still 'nil. I am not sure if or how I would go about assigning a value to it so that it corresponds to the exact price associated with that pin.

class ChargesController < ApplicationController

    def create
      # Amount in cents
      @pin = Pin.find(params[:id])
      @amount = (@pin.price * 100).floor

      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :card  => params[:stripeToken]
      )

      charge = Stripe::Charge.create(
        :customer    => customer.id,
        :amount      => @amount,
        :description => 'Rails Stripe customer',
        :currency    => 'usd'
      )

    rescue Stripe::CardError => e
      flash[:error] = e.message
      redirect_to charges_path
    end

end

Also, whatever button or link calls the ChargesController#create method is likely in the code below here in the pins show.html.erb:

app/views/pins/show/html.erb

      <% if @pin.user == current_user %>

          <%= form_tag charges_path, id: 'chargesForm' do %>
              <script src="http://ift.tt/1doUtf9"></script>
              <%= hidden_field_tag 'stripeToken' %>
              <%= hidden_field_tag 'stripeEmail' %>  
              <button id="btn-buy" type="button" class="btn btn-success btn-lg btn-block"><span class="glyphicon glyphicon-heart"></span>   I want this!</button>

              <script>
                  var handler = StripeCheckout.configure({
                    key: '<%= Rails.configuration.stripe[:publishable_key] %>',
                    token: function(token, arg) {
                      document.getElementById("stripeToken").value = token.id;
                      document.getElementById("stripeEmail").value = token.email;
                      document.getElementById("chargesForm").submit();
                    }
                  });
                   document.getElementById('btn-buy').addEventListener('click', function(e) {
                    handler.open({
                      name: <%= @pin.manufacturer %>',
                      description: '<%= @pin.description %>',
                      amount: '<%= (@pin.price * 100).floor %>'
                  });
                  e.preventDefault();
                 })
              </script>
          <% end %>

      <% else %>

          <%= link_to 'I want this!', new_user_registration_path, class: "btn btn-success btn-lg btn-block" %>

      <% end %>

   <ul id="details-infobox" class="list-group">
          <li class="list-group-item active clearfix">DETAILS</li>
          <li class="list-group-item">
            <p><strong>Description:</strong>   <%= @pin.description %></p></li>
          <li class="list-group-item clearfix">
            <span class="pull-left content-qualifier"><b>Price: $ <%= @pin.price %></b></span>

          </li>
        </ul>
    </aside>

</section>

What should I do to patch this issue? Thanks!

ActiveRecord::Base#assign_attributes monkey patch doesn't work after Rails 4 upgrade

I'm upgrading an existing Rails 3 upgrade to Rails 4. This application monkey patches ActiveRecord::Base#assign_attributes and was working fine in Rails 3; now in Rails 4 the monkey patched code never gets called.

I have a config initializer which requires the monkey patched code from the lib directory and I can see that it is run once during the startup initialization process.

This is a simplified version of the monkey patch file from the lib directory.

# encoding: UTF-8
module ActiveRecord
  class Base
    alias_method :default_assign_attributes, :assign_attributes

    def assign_attributes(new_attributes)
      # Do some custom stuff here
      default_assign_attributes(new_attributes)
    end

  end
end

Rails authenticate mongodb_logger with devise

I've got installed gems mongodb_logger and devise.
I was wondering how to restrict access to users who are registered in devise ?
I tried as follows( restricting to users with admin role)

authenticate :user, ->(u) { u.admin? } do
mount MongodbLogger::Server.new, at: "/mongodb_logger", as: :mongodb_logger,

in my routes.rb. But this didn't help... How can I do such a thing ?

RSpec controller inherited with base controller

I have this in my controller:

class API::UsersController < API::BaseController

And I generated rspec for this but I kept getting error with:

uninitialized constant API::BaseController (NameError)

This is what I did in rpsec. What is wrong here. Thanks!

require 'rails_helper'

describe API::V4::M0::UsersController do

end

collection_select could not pull up list

I was wondering if anybody can help me with this small issue that i am facing.. I am trying to fix my collection_select function on my "address" edit controller.. in my views

edit.html.erb

<%= form_for(@address) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= hidden_field_tag :customer_id, @customer.id %>

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

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

.
.
.

<%= f.label :owner_id %>
<%= f.collection_select :owner_id, @owners, :id, :name, {:include_blank => 'no owners', :prompt => true}, class: 'form-control' %>

.
.
.
<%= f.submit "Edit address", class: "btn btn-primary" %>

in my controller

def edit
@address = Address.find(params[:id])
@customer = Customer.find(params[:id])
@owners = Owner.where(customer_id: @customer.id)
end

This can't work as there will be no owners showing up even thought i have already related them to the specific customer using customer_id in the owners table.

i have tried to change my controller edit code to:

def edit
@address = Address.find(params[:id])
@customer = Customer.find(params[:id])
@owners = Owner.where(customer_id: 75)
end

and this WORKS, as it pulls all owners with customer_id: 75

I have even changed the link into the edit form to include the customer_id into the params like below:

<%= link_to "", edit_address_path(address, :customer_id => @customer.id), remote: true, class: "glyphicon glyphicon-edit" %>

Can anyone help me? will greatly appreaciate as i know it might be just a small error on my coding part.

Net::SMTPAuthenticationError in UsersController#create

our Rails 3.2 application's "resend activation code" mail feature was working until the code was transferred from the previous developer to us. Now we get this error

Net::SMTPAuthenticationError in UsersController#create  

Our mail settings remain untouched like this:

ActionMailer::Base.smtp_settings = {  
:address              => "smtp.sendgrid.net",  
:port                 => 587,  
:domain               => "example.com",  
:user_name            => "username",  
:password             => "password",  
:authentication       => "plain",  
:enable_starttls_auto => true  
}  

We are somehow not able to figure it out as to why the email stop's working.
We have checked the gmail server also responding back to us via telnet.
We have also enabled the Less Secure Apps feature of Gmail's in Security -> Account permissions -> Access for less secure apps
Thanks in advance.

mardi 21 juin 2016

rails save record to table before validating?

So I have basically an invoice, and the post_status is nil and when its set to closed, users cant edit it anymore.

validate :post_status, :if => :opened?
def opened?
    if (post_status == 'Closed')
        errors.add(:base, "Already Closed")
        return false
    end
    return true
end

this is what i have but when I set to closed, it already starts validating it and so I cant really set it to closed. I want it to be able to set my post_status to closed, so then the next time I want to edit, I cant edit anymore because its already closed.

How to use validates_uniqueness_of an id but only for some items out of a list of items with the same id. rails

I have two drop down lists. One that contains items with bmp_id and a sublist that includes items with that bmp_id (in this case it is 2) that each have a unique bmpsublist_id. One of the options from the main dropdown list includes five sublist options with the bmpsublist_id's [3, 4, 5, 6]. I want to make it so that the user can only have ONE of the sublist choices with bmpsublist_id's [4, 5, and 6] the bmpsublist_id should not be unique and would be able to be added regardless of whether the others have been added. When you submit the form, the bmp_id and bmpsublist_id are added to a table called Bmp.

This is the validation I'm using in my model:

validates_uniqueness_of :bmp_id, :message => "TODO", if: "bmpsublist_id == 4 || bmpsublist_id == 5 || bmpsublist_id == 6 || bmpsublist_id == 7"

The issue with this validation is that if you add option with bmpsublist_id 3 first, you can no longer add those with bmpsublist_id's of 4, 5, and 6 which I want to still be able to add one even if a record with bmpsublist_idof 3 has already been added. But if you add one of the ones with bmpsublist_id's of 4, 5, or 6, you can still add the one with 3 which I don't want to change.

Any ideas? Sorry if this is super confusing. I don't really know how to explain things very well.

UPDATE:

I figured it out, answer is below

Rails 3 upgrade to Rails 4 url_for no longer working, need to call ActionView::RoutingUrlFor#url_for?

I'm in the process of upgrading an existing application from Rails 3 to Rails 4. I have an internal gem that needs to use the url_for gem to return URLs for a form that will be rendered.

In Rails 3 I was accomplishing this using

@template.url_for(:controller => '/foo', :action=> 'bar')

In Rails 4 this ends up using a generic method that really does nothing and actually raises an exception if passed a hash.

It appears the real logic of the old url_for has moved into ActionView::RoutingUrlFor#url_for, but I'm not sure how I can call this from outside the view now?

Rails Devise Ajax - Successful login but refresh the page and I'm not logged in

Using an overridden devise method (this is Devise 3.0.2) it seems I have a successful login via ajax. But if I refresh the page I am not logged in.

The overridden method is as follows:

 def create
    resource = User.find_for_database_authentication(email: params[:user][:email])
    return invalid_login_attempt unless resource

    if resource.valid_password?(params[:user][:password])
      sign_in :user, resource
      after_sign_in_path_for(resource)
      return render :json => {status: 200}
    end

    invalid_login_attempt
  end

If I was to do the same with a standard html call it works fine. Is there anything else I need to do to remain signed in?

Thank you

ET

Rails 3 Nested Model Form with Javascript

I have created a nested model form for Lessons to Questions and Answers. It was not picking up the coffee script so I have add it the coffee code as Javascript but i am get an error and Add Question is not working. Anyone and assist please.

Lesson.rb

has_many :questions
accepts_nested_attributes_for :questions, :allow_destroy => true

Question.rb

belongs_to :lesson
has_many :answers
accepts_nested_attributes_for :answers, :allow_destroy => true

Answer.rb

belongs_to :question

application_helper.rb

def link_to_add_fields(name, f, association) new_object = f.object.send(association).klass.new
    id = new_object.object_id
   fields = f.fields_for(association, new_object, :child_index => id) do   |builder|
  render(association.to_s.singularize + "_fields", :f => builder)
end
link_to(name, '#', :class => "add_fields", :data => {:id => id, :fields =>   fields.gsub("\n", "")}) end

admin/lessons/_form.html.erb

 <%= form_for([:admin,@lesson]) do |f| %>
          <% if @lesson.errors.any? %>
            <div class="notification error png_bg">
                <a href="#" class="close"><img src="/assets/admin/icons/cross_grey_small.png" title="Close this notification" alt="close" /></a>
                <div>
                <h2><%= pluralize(@lesson.errors.count, "error") %></h2>

                  <ul>
                  <% @lesson.errors.full_messages.each do |msg| %>
                    <li><%= msg %></li>
                  <% end %>
                  </ul>
                </div>                          
            </div>
          <% end %>

  <label class="formlabel">Lesson Title</label>
  <%= f.text_field :title  %>

 <%= f.fields_for :questions do |builder| %>
 <%= render 'question_fields', :f => builder %>
 <% end %>
 <%= link_to_add_fields "Add Question", f, :questions %>

 <%= f.submit 'Save', :class => 'button' %>

_question_fields.html.erb

 <fieldset>
    <%= f.label :content, "Question" %><br />
    <%= f.text_area :content %><br />
    <%= f.check_box :_destroy %>
    <%= f.label :_destroy, "Remove Question" %>
    <%= f.fields_for :answers do |builder| %>
       <%= render 'answer_fields', :f => builder %>
    <% end %>
    <%= link_to_add_fields "Add Answer", f, :answers %>
 </fieldset>

_answer_fields.html.erb

 <fieldset>
    <%= f.label :content, "Answer" %>
    <%= f.text_field :content %>
    <%= f.check_box :_destroy %>
    <%= f.label :_destroy, "Remove Answer" %>
 </fieldset>

Here is the javascript I have added just before the end of the the head tag. I am getting an error of "$('form').on is not a function. (In '$('form').on', '$('form'....

<script>
            jQuery(function() {
              $('form').on('click', '.remove_fields', function(event) {
                $(this).prev('input[type=hidden]').val('1');
                $(this).closest('fieldset').hide();
                return event.preventDefault();
              });
              return $('form').on('click', '.add_fields', function(event) {
                var regexp, time;
                time = new Date().getTime();
                regexp = new RegExp($(this).data('id'), 'g');
                $(this).before($(this).data('fields').replace(regexp, time));
                return event.preventDefault();
              });
            });
        </script>

Response Handling equivalent in jQuery

response.rjs() => Evaluates the entire response as Javascript, as is required for Rails RJS responses.

response.execute(fn) => Calls the function object passed to it.

.on(responseStatus) =>Only execute the response function when the status code returned by the server in response to the AJAX request is responseStatus. But what will be the equivalent it in jQuery-

POST(this.up('form').action, data);
response.rjs().on(200);
response.execute(function () { 
  qPanel.hidePanel();
}).on(200);

Ruby plug in installation failed

I downloaded the ruby plugin for the sonarqube,and it is in the .rar file format.I placed it in the sonarqube/extensions/plugin folder.But when i am running the sonar-scanner it is showing that "You must install a plugin that supports the language 'ruby'".So what can i do?

how can i schedule a job at every 20 seconds using whenever gem in rails

I am trying to run a job at every 20 seconds. I am using whenever gem but as per its documentation it allows minimum 1 minute of time.

scheduler

every 1.minute do
  runner "DailyNotificationChecker.send_notifications"
end

job

i thought i can make an infinite loop and use sleep method and make it sleep for 20 seconds. that way this job will run every 20 seconds but what will happen if my cron will it this method again.

class DailyNotificationChecker 
    def self.send_notifications
        Rails.logger.info "Triggered NotificationChecker"
        if RUN_SCHEDULER == "true"
          Rails.logger.info "Running Performer"
          notes = Note.unprocessed
          if notes.present?
            notes.each do |note|
              RealtimeNotificationChecker.performer(note.user_id,"note_created")
              note_hash = {}
              note_hash[:note_id] = note.id
              url = URI.parse(PROCESS_NOTE_API_URL)
              resp, data = Net::HTTP.post_form(url, note_hash)
            end
          end
        sleep 20  #=> workaround for to sleep 20 seconds
        end
      end
end

Locking a user manually for devise rails

As a de facto standard we all using devise for login in Rails application and will use lockable module to lock user after a particular failed attempt.

from the devise source code and config.maximum_attempts = 20 I came to know that, devise perform locking when user try to give wrong login credential.

since config are statically defined at rails application boot time in initializer, My expectation is to set the maximum_attempts dynamically, is it possible? if so guide me..

I have a superadmin and user below each admin, based on the super admin I would like to set different failed_attempt value for each user during the runtime.

lundi 20 juin 2016

How to apply scoping on associations in Rails Admin

I am newbie to Ruby, Rails and Rails Admin. I came to know about scopes in ActiveRecord. I want to apply scoping to associations at the time of editing a record using the Admin interface.

Example: I have a model named Post. A post is created by some User. A user can be an admin or a normal user distinguished by relational column is_admin. At the time of creating/editing a post using the Rails Admin interface, we have to allow selection from normal user list.

I have created scope normal_users for ActiveRecord User

class User < ActiveRecord::Base
  scope :normal_users, -> { where(is_admin: false) }
end

class Post < ActiveRecord::Base
  belongs_to :user
  rails_admin do
    edit do
        configure :user do
          # _____________ ? what goes here so that only normal users are listed.
        end
    end
  end
end

Now how can I use this 'normal_users' scope in the belongs_to association in the Post so that the dropdown for the field user in the Post resource lists only the normal users.

I have seen examples filtering associations/scopes in Rails. But I do not know how to use/configure this in Rails Admin.

Meetup API integration to post event on Meetup

How to implement MeetUp API to create new event from rails application? How to authorise key to call create meet up API as I am getting 401 error code as I am free member

I have used meetup_api gem to call get events API. How to use that to Post Event ?

I have refer This and This

how to change string time to rails date format

I have date as "Wed, 29 Jun 2016" and time in "11:35 PM" format how can i create a date time object with it?

something like what Time.current does.

Chrome WebPush notifications payload encryption in ruby on rails

I have implemented webpush notification in ruby on rails using ruby(version = 1.9) and rails(version = 3.2) but it shows nil data in notification because it needs some encryption.

As per the google document, I have to encrypt payload data in given format only and then it will work. So I tried a gem webpush but the gem has only been written to support ruby 2.3. Then I tried to implement elliptic cryptography but again I'm getting nil in the gcm response So I am not sure about my encryption as well.

Thanks in advance!

Use Ajax in ruby on rails

I want send selected drop down menu value to controller by ajax

panel_controller.rb

class PanelController < ApplicationController

      def insert
         @city_ids = params[:city]
      end
end

panel.js.erb

$(document).ready(function() {
    $('#f_city_id').change(function() {
        var city_js_id = this.value
        $.ajax({
            url: '/panel/insert',
            type: 'GET',
            data: {"city": city_js_id},
            success: function (data,status)
            {
                alert(this.url);
            }
        });
        return false;
    });
});

routes.rb

get '/panel/insert' => 'panel#insert'

views/panel/insert.html.erb

<%= @city_ids %>

but @city_ids dont respond value after chenge drop down menu

ruby rails evdev not found file

I try to work with evdev on ruby rails and start the server but I get an error at startup . I want to receive Input from USB barcode.

Error is : /usr/local/lib/ruby/gems/2.3.0/gems/libevdev-1.0.0/lib/libevdev.rb:11:in class_eval': Function libevdev_set_device_log_function not found in [libevdev.so] (FFI::NotFoundError) from (eval):18:in from /usr/local/lib/ruby/gems/2.3.0/gems/libevdev-1.0.0/lib/libevdev.rb:11:in class_eval' ...

not (require ' evdev ') in Gemfile I get an error : can not load such file - evdev

please how Receive Input barcode on ruby on rails with or without evdev ?

Your Ruby version is 2.3.0, but your Gemfile specified 2.1.2

I'm trying to setup an existing project, When running bundle install, I'm getting following error.

I've tried many possible solutions but didn't worked for me, also I've run the suggested commands, like gem pristine bcrypt --version 3.1.10 but didn't work for me.

    bipashant@bipashant-Inspiron-5537:~/sanokam$ bundle install

    Ignoring bcrypt-3.1.10 because its extensions are not built.  Try: gem pristine bcrypt --version 3.1.10
    Ignoring curb-0.9.3 because its extensions are not built.  Try: gem pristine curb --version 0.9.3
    Ignoring debug_inspector-0.0.2 because its extensions are not built.  Try: gem pristine debug_inspector --version 0.0.2
    Ignoring eventmachine-1.0.3 because its extensions are not built.  Try: gem pristine eventmachine --version 1.0.3
    Ignoring executable-hooks-1.3.2 because its extensions are not built.  Try: gem pristine executable-hooks --version 1.3.2
    Ignoring ffi-1.9.8 because its extensions are not built.  Try: gem pristine ffi --version 1.9.8
    Ignoring gem-wrappers-1.2.7 because its extensions are not built.  Try: gem pristine gem-wrappers --version 1.2.7
    Ignoring gherkin-2.12.2 because its extensions are not built.  Try: gem pristine gherkin --version 2.12.2
    Ignoring http_parser.rb-0.5.3 because its extensions are not built.  Try: gem pristine http_parser.rb --version 0.5.3
    Ignoring kgio-2.8.1 because its extensions are not built.  Try: gem pristine kgio --version 2.8.1
    Ignoring mysql2-0.3.14 because its extensions are not built.  Try: gem pristine mysql2 --version 0.3.14
    Ignoring nokogiri-1.6.7 because its extensions are not built.  Try: gem pristine nokogiri --version 1.6.7
    Ignoring ruby-prof-0.14.2 because its extensions are not built.  Try: gem pristine ruby-prof --version 0.14.2

    Your Ruby version is 2.3.0, but your Gemfile specified 2.1.2

Any suggestion will be appreciated, Thank you.

Twilio start call forwarding after the prior call is disabled

I have a use case where I want to forward a call from A to C. Here if the call is already forwarded to some number i.e A to B, then I need to disable the current forwarding(i.e A to B) and then enable the new call forwarding(i.e A to C). But the new forwarding should start only if the disable call worked. I am using twilio webhook call to identify the call status. The approach I have followed is, in the method to which webhook sends response, I am checking the status of call. So when its completed, I try to find the Phone A from my apps database using call_Sid. I am storing call_Sid against the phone number that is to be forwarded. But here is the main problem.

Now when I receive status as completed for disabling I need the number to which I need to forward the call to. How should I get this new number to be passed into this method which handled twilio webhook response.

Please let me know how to achieve this.

dimanche 19 juin 2016

Issue related to method arguments in rails

I am facing some problem related to arguments passing in rails. From my controller I want to send a variable as an argument to the request handler job. But I am sure that I am doing something wrong about the variables and arguments. Student is the model name. Actually the students table contains some records. I am facing the following problem.

formal argument can not be an instance variable.

Here is my code:

My app/controllers/students_controller.rb file is:-

class StudentsController < ApplicationController

attr_accessor :xmodel
def new
    @student=Student.new
    @students=Student.all
end

def create
    @student=Student.new(u_params)
    @student.set_insertbool_field

    xmodel=Student.last
    RequestHandlerJob.doit_later(:xmodel)

    if @student.save
        redirect_to new_student_path
    end
end


 def u_params
   params.require(:student).permit(:id , :firstname, :lastname)
 end

end

My app/jobs/request_handler_job.rb file is:

class RequestHandlerJob < ActiveJob::Base
queue_as :default

self.queue_adapter = :sidekiq


def doit_later(:xmodel) 
 # Do something later
 @extract_bool=:xmodel.inserted_bool
  if @extract_bool == 1
    redirect_to new_student_path , :notice => "Inserted and Queued"

  end
 end
end

miss template when respond CSV

I have a action to download file csv, but when click error missing template

Code in my action

def export 
    respond_to do |format|
      format.html
      format.csv { send_data UserDetail.order('id desc').first(20).to_csv }
    end
  end

In my view:

= link_to "Export CSV", export_call_center_user_details_path(format: "csv"), :class => "btn btn-default"

error:

Processing by CallCenter::UserDetailsController#export as CSV Completed 500 Internal Server Error in 5ms

A ActionView::MissingTemplate occurred in user_details#export:

Missing template call_center/user_details/export, application/export with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee, :haml]}.

When i try remove line format.html so error:

Completed 406 Not Acceptable in 4ms (ActiveRecord: 0.3ms)

How to fix error above?

samedi 18 juin 2016

Update attribute isn't working for my ids list?

On my site you can open sessions, and add instruments to the session. An admin (the person who creates the session) can choose what instruments are in the session.

In this example we will say "The admin wants the following instruments: 1, 1 again and instrument 2". So far everything proceed as expected but then... #{start.exciting.music.now}

The admin wants to add another instrument but if the instrument already exist you can't add it again?

Edit form

  .col-xs-12.item
    %hr
    %ul#instrument-selection.instrument-list
      = link_to instruments_path, class: 'fancybox' do
        %li
          = image_tag('plus.png', class: 'fit')
          Add instrument
      - @meeting.instruments.each do |instrument|
        %li
          = image_tag(instrument.icon_path)
          = instrument.name
          %input{type: 'hidden', value: instrument.id, name: 'meeting[instrument_ids][]'}
          %i.fa.fa-times.delete-me

What you open when you click on the fancy box link

%section#musician-listing
  .col-xs-12.item
    .musician-badge
      %ul.musician-info
        - @instruments.each do |instrument|
          %li.col-xs-12.item
            .col-xs-6
              = image_tag(instrument.icon_path, class: 'fit instrument-icons')
            .col-xs-6
              = link_to '#', class: 'btn btn-success fit square add-instrument', data: {instrument_id: instrument.id, name: instrument.name, icon: "/#{instrument.icon_path}"} do
                Add
                = instrument.name
        .clearboth

Meeting controller

  def create
    meeting = current_user.meetings.create( meeting_params )
    if meeting.valid?
      redirect_to meeting
      flash[:notice] = "Succesfully created session"
    else
      redirect_to new_meeting_path
      flash[:alert] = "Oops.. You haven't filled in the required information"
    end
  end
  def update
    meeting = current_user.meetings.find(params[:id])
    meeting.update_attributes(meeting_params)

    redirect_to meeting
    flash[:notice] = "Succesfully edited session"
  end

The output when updating the meeting (seems fine I guess)

Started PATCH "/meetings/163" for 127.0.0.1 at 2016-06-18 22:29:41 +0200
Processing by MeetingsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZJvwuX3x4f7cACp5N75IOEn7zczO4qyevmxydiN+LF+AZnys11kioeAbUU/jwlc76+mAdN2c2vvZKFpgg+6vPA==", "meeting"=>{"title"=>"Test2", "closed_session"=>"false", "genre_id"=>"2", "instrument_ids"=>["1", "1", "1", "1", "2"], "user_ids"=>["2"]}, "commit"=>"Update session", "id"=>"163"}

Now the weird part!

Even if the "instrument_ids" returns ["1", "1", "1", "1", "2"] it just removes the 3th and the 4th "1" and it keeps the "2".

If we would update it again (before updating the array is ["1", "1", "2"]) and for example we add another "2" and a "5" and another "1", the PATCH command will return ["1", "1", "2", "2", "5", "1"] but it will end up with ["1", "1", "2", "5"].

Again everything what already exist is removed

If you create a new meeting you can add as much the same ids if you like.

Any help would be much appreciated it's driving me mad....

Cheers, Chris

P.S. staring at this issues for almost 12 hours... haha damn....

vendredi 17 juin 2016

google_visualr Image Bar chart label not in place

I am using google_visualr gem. The GoogleVisualr::Interactive::ColumnChart generating correct chart but in GoogleVisualr::Image::BarChart labels are not on the right place in images. See below scrrenshots.

GoogleVisualr::Interactive::ColumnChart

enter image description here

GoogleVisualr::Image::BarChar

enter image description here

Any suggestion that how can i render chart with my html data? where i am going wrong?

I am using rails 3 and 'google_visualr', '>= 2.1'

Rails override id on create controller with user specified id in forms in new.html.erb

To change an id in rails its like Invoice.create(id: 25) works but in my new.html.erb, i have user specify an id (:invoiceid) and i want that id to be linked to that id.

so how do you do it? Invocie.create(id: invoiceid) wont work.

Disabling JavaScript when using Capybara + Selenium

I have an app that's designed to still be functional when JavaScript is disabled, so I wanted to write some specs that covered those cases.

I'm using Selenium (Firefox) with Capybara and I'm registering an new driver with JavaScript disabled (via Selenium's javascript.enabled property)

# spec/rails_helper.rb
Capybara.configure do |config|
  config.ignore_hidden_elements = true
  config.default_driver = :selenium
end

Capybara.register_driver :disable_js do |app|
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile["javascript.enabled"] = false
  Capybara::Selenium::Driver.new(app, profile: profile)
end


# spec/features/siging_in_spec.rb
context "JavaScript disabled", driver: :disable_js do
  it "user can still sign in" do
    # ...
    # ...
  end
end

The feature specs are failing to actually disable JavaScript. When the browser window pops up during testing and I pause it with binding.pry, I can definitely click around on items I know require JavaScript and see them working.

Side note: If I actually go to my Firefox settings and disable JavaScript, the test passes. So it appears it's inheriting whatever configuration I set in my browser, and not actually using the configuration specified when registering the driver.

Is this the correct approach here, or is there something I missed?

Thanks!

Getting undefined method `each' for "":String in Rails after submitted

Getting this error after submitted the form.

  def create
@user = User.new(user_params)
if @user.save
  log_in @user
  redirect_to @user
else
  render 'new'

end

end

Rails server not loading application.css

Already apologize for the dumb question. I've been studying about ruby and rails not for long, so do not know much about rails.

I'm starting to work with an old application, and managed to install ruby , rails and mysql into Ubuntu 14.04 LTS, and I'm able to run the server without a problem, but it's not being able to run any css file from app/assets path. From start the app couldn't run any javascript either, and I managed to make it work by removing the equals sign from the require code, at the top of app/assets/javascript/application.js file:

// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://ift.tt/1nyjx9R
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// require jquery     (was //= require jquery)
// require jquery_ujs (was //= require jquery_ujs)
// require_tree .     (was //= require_tree .)

I could make the page load the css if I paste the stylesheet folder from app/assets to public folder, but I know the app is running the correct path in the server where it's running.
So, what could I be missing to get my assets to load app/assets/stylesheet files, besides public/stylesheet?

Just for info, here's the ruby and rails versions (pretty old by the way, another problem I should solve next):
Ruby = ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-linux]
Rails = Rails 3.1.3