Monday, May 2, 2016

Rails 4 Associations: Help setting up database | Fixed issues

Rails 4 Associations: Help setting up database | Fixed issues


Rails 4 Associations: Help setting up database

Posted: 02 May 2016 06:55 AM PDT

I need some assistance with my Rails 4 associations. I have the following 4 models:

class User < ActiveRecord::Base      has_many :check_ins      has_many :weigh_ins, :through => :check_ins      has_many :repositionings, :through => :check_ins  end    class CheckIn < ActiveRecord::Base      belongs_to :user      has_one :weigh_in      has_one :repositioning  end    class Repositioning < ActiveRecord::Base      # belongs_to :user      belongs_to :check_in  end    class WeighIn < ActiveRecord::Base      # belongs_to :user      belongs_to :check_in  end  

Question: If I am setup this way, how would I input repositionings and weigh_ins separately, but still have them linked through a single check in?

Rails routing sometimes replaces the id in url with id-name. How do I avoid problems?

Posted: 02 May 2016 06:56 AM PDT

Generally the url from my report page looks like this:

 http://test-account.peter:3000/offices/7/reports/index  

However, sometimes it looks like this:

 http://test-account.peter:3000/offices/7-peters-office/reports/index  

Why does this happen?

It was not really a problem until we changed the controller action from a GET to a POST and renamed it. We had to do this so we could pack more parameters in to the ajax request. Users still have this section of the site bookmarked and it throws errors all day long.

I have tried to redirect the route:

   get '/offices/*all/reports/index' => 'offices#show'     get '/offices/:office_id/reports/index' => 'offices#show'     get '/offices/:office_name/reports/index' => 'offices#show'  

Is there a way to catch the name? Or do I have to prevent the name from being added to the url in the first place?

When deploying my Rails 4 application with Capistrano, how to avoid a user timeout error?

Posted: 02 May 2016 06:37 AM PDT

I deploy my project to my production server using the capistrano gem. Everything works fine, however, I've noticed that if my users are accessing the site right when my deployment is trying to wrap things up - they can get an error notice that there was a "timeout" with the server.

How can I handle this so at most is just a little longer of a wait for the user? Currently, in my database.yml config I have the timeout set to: timeout: 5000. Should I just up this to like 15000 ? Or are there some significant downsides to doing that?

Testing whether geocoding happens before_validation

Posted: 02 May 2016 06:25 AM PDT

we're using geocoder gem within a Rails 4.2 Application. Geocoding happens for a places model with address attributes (:street, :postal_code, etc.) using the geocoder gem with nominatim as the API of our choice. Now, I wanted to test whether geocoding is happening accordingly places_controller using Minitest, unfortunately the following problem occurs using a valid (really existing) address

# Test geocoding ability    test 'place address should geocode to lat/lon' do      post :create, place: { name: 'foo',                             street: 'Magdalenenstraße',                             house_number: '17',                             postal_code: '10365',                             city: 'Berlin',                             categories: 'bar' }        new_place = Place.find_by_name('foo')      assert_not_nil new_place.latitude      assert_not_nil new_place.longitude    end  

Within the places model the geocoding is set to before_validation, hence I was expecting that lat/lon is being set (automatically by the gem) before the validation is being applied. Obviously this does not seem to happen as the test fails with undefined method 'latitude' for nil:NilClass (=> post not successfull because no lat/lon has been supplied). Can anyone tell me why and how to solve that problem?

Thanks in advance!

Cloud9 Warning do I just ignore?

Posted: 02 May 2016 06:29 AM PDT

During testing in chapter 3 I get the following warning, is this ok to ignore?

RubyDep: WARNING: your Ruby is outdated/buggy. Please upgrade. (To disable >warnings, set RUBY_DEP_GEM_SILENCE_WARNINGS=1) Run options: --seed 18589

Thanks Gaz Smith

Rails ajax dropdown menu set selected

Posted: 02 May 2016 06:30 AM PDT

I have ajax script which selects necessary data and returns array

server response

[{"id":67,"title":"first","selected":"first"},   {"id":68,"title":"second","selected":"first"},   {"id":69,"title":"third","selected":"first"},    {"id":70,"title":"fourth","selected":"first"}]  

script

$(document).ready ->    category_id = $('#product_category_id').attr('selected', 'selected').val()    product_id = $('#product_id').val()    $.ajax      type: 'GET'      url: "/products/dynamic_admin_subcategory?category_id=#{category_id}&id=#{product_id}"      dataType: 'json'      success: (data) ->        $('#product_subcategory_id').empty()        subcat = $('#product_subcategory_id')        $.each data, (value, key) ->          console.log(key)          $("<option />", {value: key.id, text: key.title}).appendTo(subcat);          $("#product_subcategory_id option:selected").val(key.id).text(key.selected)        return    return  

It works fine, but I cant set selected

Also i have tried

  $("#product_subcategory_id option[value=key.selected]").prop("selected", "selected")  

but cant pass value to option[value=key.selected] What should i do?

use params[:file] as parameter for ActiveJob

Posted: 02 May 2016 06:10 AM PDT

I have a form with a file upload field, which sends a params[:file] when submitted. I want to use this param as a parameter for an job like this:

ImporterJob.perform_later(params[:testrun][:file])  

This however returns an error:

ActiveJob::SerializationError in TestrunsController#create  Unsupported argument type: ActionDispatch::Http::UploadedFile  

Is it possible to send a file parameter to a job?

Ruby on rails - bootstrap material design - Add checkboxes to simple form

Posted: 02 May 2016 06:13 AM PDT

I installed the Bootstrap Material Design in my Ruby on Rails application and every animation is functioning properly, but i can´t see the checkboxes. My code for the checkboxes is:

<div class='form-group'>    <div class='control-label col-sm-2'>    </div>    <div class='col-sm-8'>      <%= f.input :active, :as => :boolean, :label => false, :inline_label => true %>    </div>  </div>  

Can anyone Help me please?

Thank you all!

ActiveRecord single table inheritance - how to get root model?

Posted: 02 May 2016 06:20 AM PDT

I have a model using single table inheritance and a concern that should work on any model.

Consider this example:

class Car    acts_as_categorizable  end    class Suv < Car; end    module Categorizable    def after_safe      siblings = this.class.where(category: self.category)      #... do something with the siblings    end  end  

Now if I have an Suv and manipulate its category, the siblings line will only find the other Suv cars in that category, but I need to find all cars in that category.

I don't want to hardcode this, so given a Suv class, I need to find its root model (Car).

Possible Poltergeist memory leak - how to use session.driver.quit?

Posted: 02 May 2016 05:35 AM PDT

I think I'm running into a memory leak when running Rspec/ Capybara tests. At least, this reasonably high-specced Macbook Pro — and Chrome in particular — slows to an almost unusable crawl when tests are run.

Poltergeist mentions this as a possible issue (I am running JS tests).

The suggested fix is to include session.driver.quit, but where should this be included? Where is session defined by default?

When I include session.driver.quit after tests it causes errors.

Simple form calling undefined url helper when generating a form for a nested resource within a namespace

Posted: 02 May 2016 05:40 AM PDT

Greetings everyone,

I have the following routes:

  namespace :hr do      resources :employees do        resources :skills      end    end  

And the following controllers:

hr/employees_controller.rb
hr/skills.rb

The generated route url helper for an Hr::skill scoped by an Hr::Employee would be:
hr_employee_skill_path(employee_id, skill_id)

However when using simple_form:
simple_form_for [@hr_employee, @hr_skill]
It wrongly uses an undefined URL helper:
hr_employee_hr_skill_path.

I know it's possible to manually set the URL when invoking #simple_form_for, but that would mean the form cannot be fully shared between edit/new views(without any tweaking at least.)

Why is simple form calling undefined URL helpers that way? And what can I do to make it call the right ones properly?

Wait for Ajax call to finish for Capybara

Posted: 02 May 2016 05:11 AM PDT

I am fetching data from a server(via ajax) using 3 select dropdowns. I want to write an integration test where I need to wait for the ajax request to finish then select a value from the next dropdown.

So far I am waiting for some seconds before doing the next select but that's not reliable and not a good solution.

Arel and ActiveRecord's count throws error

Posted: 02 May 2016 04:58 AM PDT

I'm trying implement a library function which should return ActiveRecord relation. Complex SQL query is done with Arel. It has to work on multiple database backends so raw SQL queries are the last resort.

Simplified example:

Spree::Product < ActiveRecord::Base  end    prod_at = Spree::Product.arel_table    # select record's ids by Arel attribute  > Spree::Product.select(prod_at[:id])     Spree::Product Load (0.9ms)  SELECT "spree_products"."id" FROM     "spree_products" WHERE "spree_products"."deleted_at" IS NULL     => #<ActiveRecord::Relation [#<Spree::Product id: 14>, #<Spree…    # previous call converted to SQL, generates correct query  > Spree::Product.select(prod_at[:id]).to_sql    SELECT "spree_products"."id" FROM "spree_products" WHERE    "spree_products"."deleted_at" IS NULL    # Surprisingly, applying ActiveRecord::Calculations.count fails  > Spree::Product.select(prod_at[:id]).count    ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error    at or near "Arel"    LINE 1: SELECT COUNT(#<struct Arel::Attributes::Attribute relation=#...                                ^    : SELECT COUNT(#<struct Arel::Attributes::Attribute relation=#<    Arel::Table:0x00000007553f50 @name="spree_products",    @engine=Spree::Product(id: integer, …  

It looks like .count methods does not unwind embedded Arel expression to SQL and passes it as-is.

Even more surprising, other methods from ActiveRecord::Calculations work correctly, even comparable .calculate :

> Spree::Product.select(prod_at[:id]).calculate(:count, :id)    (0.5ms)  SELECT COUNT("spree_products"."id") FROM "spree_products" WHERE    "spree_products"."deleted_at" IS NULL    => 1253  

Any idea what am I doing wrong ? How adjust Arel object to work also with count method ? Some workaround ?

I have to return ActiveRecord_Relation. The affected count method is called from other 3rd party module which can't be directly modified.

Rails 4 - Custom Validation Error

Posted: 02 May 2016 05:28 AM PDT

This is my model -

class Leave < ActiveRecord::Base  belongs_to :staff  validates :staff, :leave_type, :start_date, :end_date, :number_of_days, :approved_by, presence: true  enum leave_type: {Medical: 0, Annual: 1, Urgent: 3, "Birth Leave": 4}  validate :check_leave, :if => "self.number_of_days.present?"          protected    def check_leave    if self.leave_type = 0      if ( self.number_of_days + LeaveAllocation.last.medical_leave_counter ) > LeaveAllocation.last.medical_leave        self.errors.add(:number_of_days, "Days exceeded the limit")      end    end    if self.leave_type = 1      if ( self.number_of_days + LeaveAllocation.last.annual_leave_counter ) > LeaveAllocation.last.annual_leave        self.errors.add(:number_of_days, "Days exceeded the limit")      end    end    end    end  

When I try to run the validation, it only seems checks the first one "0" even if i change the selection to "1". Any help would be appreciated! Thanks

I have to click confirm around 5 times when i delete something in my Rails app [on hold]

Posted: 02 May 2016 05:20 AM PDT

I have to click 'confirm - yes' around 3-6 times each time i want to delete a note on my notebook application, any ideas why? I have includes a before_action in the controller that includes the destroy function of CRUD:

before_action :find_note, only: [:show, :edit, :update, :destroy]  

Here is the destroy code itself:

def destroy      @note.destroy      redirect_to notes_path  end  

solr sunspot unicode? characters

Posted: 02 May 2016 04:43 AM PDT

How do I use this file provided in sunspot (mapping-ISOLatin1Accent.txt)(or is this the one I need as well)? I need to be able to search for "las pinas" and include results like "las piñas" in my database. Meaning n => ñ? I have my config schema.xml like this for now:

<fieldType name="text" class="solr.TextField" omitNorms="false">    <analyzer>      <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>      <tokenizer class="solr.StandardTokenizerFactory"/>      <filter class="solr.StandardFilterFactory"/>      <filter class="solr.LowerCaseFilterFactory"/>      <filter class="solr.PorterStemFilterFactory"/>      <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="false" tokenizerFactory="solr.StandardTokenizerFactory"/>    </analyzer>  </fieldType>  

and I have tried moving the <charFilter> setting around as well.

I have also searched and found various solutions mostly pointing to this or this articles but those don't seem to work either.

Cast old string values to datetime with migration in Rails PostgreSQL

Posted: 02 May 2016 06:39 AM PDT

I had a couple of date fields in a database table, however they are firstly initiated as string, not datetime. Therefore, I wanted to change those value types to datetype with a migration,

class ChangeDateColumnsToDateTime < ActiveRecord::Migration    def change      change_column :users, :flight_date_departure, :datetime      change_column :users, :flight_date, :datetime      change_column :users, :appointment_date, :datetime    end  end  

however it can not cast old string values to datetimes that exists in database currently, saying that PG::DatatypeMismatch: ERROR: column "flight_date_departure" cannot be cast automatically to type timestamp without time zone. HINT: You might need to specify "USING flight_date_departure::timestamp without time zone". We've done it without problem in a SQLite database, however there is this problem for PostgreSQL. How can I modify my migration so that I do not lose old values and properly convert them to datetime?

Ajax - Why isn't my remote rails form exucuting create.js.erb?

Posted: 02 May 2016 04:49 AM PDT

I'm getting this error each time i try to post a comment although when I refresh the paage comments are displayed

HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request. (XHR): POST - http://website.com/posts/37/comments

in chrome I got

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

in my comments controller

if @comment.save        respond_to do |format|          format.html do            flash[:success] = 'Comment posted.'          end          format.js # JavaScript response        end      end  

and I set the form to remote: true

so its supposed to execute the code in create.js.erb which is

console.log('working?')  alert('working?')  

commenting is working but the format.js is not

heres the trace

ActionView::Template::Error (undefined local variable or method `comment' for #<#<Class:0x007f3db84dd300>:0x007f3db9aff0e8>  Did you mean?  @comment):      1: console.log('done')      2: alert('done?')      3: //$('comment-<%= comment.parent.id unless comment.parent.blank? %><%= "-".html_safe  unless comment.parent.blank? %><%= comment.id %>').load(location.href + " comment-<%= comment.parent.id unless comment.parent.blank? %><%= "-".html_safe  unless comment.parent.blank? %><%= comment.id %>");      4: //$('comment-<%= comment.parent.id unless comment.parent.blank? %><%= "-".html_safe  unless comment.parent.blank? %><%= comment.id %>').html('<% j (render 'comments') %>')      5: //console.log(comment.parent.id unless comment.parent.blank? %><%= "-".html_safe  unless comment.parent.blank? %><%= comment.id %>)    app/views/comments/create.js.erb:3:in `_app_views_comments_create_js_erb___4383133957853497951_69951529166680'    app/controllers/comments_controller.rb:21:in `create'        Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (3.8ms)    Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (1.4ms)    Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb (72.2ms)  

Matching Signed Headers Encrypted in Ruby on Rails and JavaScript

Posted: 02 May 2016 03:59 AM PDT

I am using ApiAuth gem (as found here) to sign my request. I am also writing my own JavaScript code using CryptoJS (as found here) to provide authentication by checking the encrypted header generated by ApiAuth against the one generated by my code.

Given below is a code snippet from ApiAuth Gem:

def hmac_signature(headers, secret_key, options)    if options[:with_http_method]      canonical_string = headers.canonical_string_with_http_method(options[:override_http_method])    else      canonical_string = headers.canonical_string    end    digest = OpenSSL::Digest.new('sha1')    b64_encode(OpenSSL::HMAC.digest(digest, secret_key, canonical_string))  end  

Here is the code I have written as an equivalent in JavaScript:

function hmacSignature(request, appSecret) {   return CryptoJS.HmacSHA(canonicalString(request), appSecret).toString(CryptoJS.enc.Base64);}  

These two don't generate the same encrypted header. I tried using jsSHA to do the same thing and while the encrypted header generated by jsSHA and CryptoJS is the same, they don't match the one generated by ApiAuth.

Kindly help me figure out how to make this work.

Pass data to modal

Posted: 02 May 2016 04:02 AM PDT

Sorry for that question, googled a lot.. but I cant find a solution.. I am using materialize css (not twitter) and want to pass an ID in a modal

HTML

<%= link_to 'Modal', '#modal3', :data => {:toggle => 'modal', :data_id => '123'}, :class=> 'modal-trigger' %>  

COFFEE

$('.modal-trigger').leanModal()   ready: ->    $("#canvas").load($(this).data('id'))    return  

In Modal

<div id="canvas" ></div>   

Thanks for helping..

ruby on rails braintree fail on duplicate payment method

Posted: 02 May 2016 03:51 AM PDT

i am trying to implement braintree payments into a ruby app, and everything seems to be working fine, but when i pass fail_on_duplicate_payment_method_card as an option i am getting invalid keys: options[fail_on_duplicate_payment_method_card]

result = Braintree::PaymentMethod.create(          :customer_id => current_user.customer_cim_id,          :payment_method_nonce => 'fake-valid-amex-nonce',          :cardholder_name => "#{current_user.first_name} #{current_user.last_name}",          :options => {              :make_default => true,              :fail_on_duplicate_payment_method_card => true          }      )      if result.success?        customer = Braintree::Customer.find(current_user.customer_cim_id)        puts customer.id        puts customer.payment_methods[0].token      else        p result.errors      end  

Ruby on Rails server requirements

Posted: 02 May 2016 06:31 AM PDT

I use rails for small applications, but I'm not at all an expert. I'm hosting them on a Digital Ocean server with 512MB ram, which seems to be insufficient.

I was wondering what are Ruby on Rails server requirements (in terms of RAM) for a single app.

Besides I can I measure if my server is able to support the number of application on my server?

Many thanks

ActionView::Template::Error (singleton can't be dumped)

Posted: 02 May 2016 05:10 AM PDT

I am using gem 'jbuilder_cache_multi' for cache my json responses. I am encountering a strange error when i hit my api from my ios native app. Below is the error i got:

ActionView::Template::Error (singleton can't be dumped):  2:  3: json.orders do  4:   json.cache! ['v1', I18n.locale, @orders] do  5:     json.cache_collection! @orders, key: ['v1', I18n.locale] do |order|  6:       json.partial! 'order', order: order  7:     end  8:   end    app/views/api/v1/orders/index.json.jbuilder:5:in `block (2 levels) in   

Request is:

Started GET "/api/v1/orders?page=2&q%5Bmerchant_id_eq%5D=1&q%5Bs%5D=created_at+asc&q%5Bstate_not_in%5D%5B%5D=composing&q%5Bstate_not_in%5D%5B%5D=distributed&q%5Bstate_not_in%5D%5B%5D=canceled"   

Can anyone help in this regard. Thanks

Ruby on Rails 4/ Turbolinks - how to disable turbolinks on a Rails UJS (ajax xhr) call

Posted: 02 May 2016 04:41 AM PDT

On a Deal page, I have a Rails UJS call. It loads a modal. The problem is the following:

  • I am on the homepage with a list of deals

  • I then click on a Deal n°4

  • I arrive on the Deal n°4 page

  • I click the button that point to a modal (here using Rails UJS)

  • The modal appears

  • I press chrome "back" button which makes me go back to the homepage

  • I reclick on the link "Deal n°4" to go back to the Deal page n°4

  • I arrive on the Deal page n°4

  • and here is the problem: when I click again the button that should trigger the modal to appear , the modal DOES NOT appear.

I am 100% sure it's due to turbolinks as I removed it and then it works.

I want to keep generally turbolinks but to disable it only for this AJAX call.

I read all i can think of on SO and the web but nothing works.

CODE

(note: on the hompeage: just the list of the deals and I can click on a deal- it's a standard link)

Deal page

html

<div id="modal-zone">          <div class="insider">        <span>          <%= link_to image_tag(smallest_src_request),                modal_path,                remote: true,                class: "link",                alt: "loadin'" %>        </span>      </div>    </div>  

When the user clicks the Rails UJS link, it points to views/modal.js.erb (I am using hubspot Messenger also as below)

var msg;  msg = Messenger().post({    message:  'This is your participation number X to the deal',      hideAfter:  false    });   

In terms of html, this modal is:

<ul class="messenger messenger-fixed messenger-on-bottom messenger-theme-flat">    <li class="messenger-message-slot messenger-shown messenger-first messenger-last">      <div class="messenger-message message alert error message-error alert-error">        <div class="messenger-message-inner">This is your participation number X to the deal  <br>        </div>      </div>    </li>  </ul>  

I tried adding directly of via a jquery injection data-no-turbolink to those different places and it never worked

on the main link_to with the Rails UJS

<%= link_to image_tag(smallest_src_request),                modal_path,                remote: true,                data: { no_turbolink: true } " %>  

or even on the parent div of the modal:

<ul class="messenger messenger-fixed messenger-on-bottom messenger-theme-flat" data-no-turbolink: "true">  

But nothing worked.

I feel what the techniques I tried using are only working when you want to disable turbolinks on a on page:load, or page:change but not when you need to disable it ON the elements that are loaded on an event I don't actually know the name but which is kind of "page:ajaxcall", that is to say on the content loaded by an ajax call by Rails UJS.

NGINX Config: How to match any filetype or subfolder of given path?

Posted: 02 May 2016 05:30 AM PDT

I need to bypass rails via NGINX for any requests that fall beneath a certain path for various assets such as:

test.com/inc/js/test.js     -> /var/www/test/public/example/inc/js/test.js    test.com/inc/js/another/subfolder/test.js     -> /var/www/test/public/example/inc/js/another/subfolder/test.js    test.com/inc/css/test.css     -> /var/www/test/public/example/inc/css/test.css    test.com/inc/css/any/given/subfolders/test.css     -> /var/www/test/public/example/inc/css/any/given/subfolders/test.css  

I am currently trying to edit the nginx config such that any web request maps to the appropriate file:

location ~* /inc {      root /var/www/test/public/example/inc;      try_files $uri =404;  }  

Which isn't working - I assumed that any request of /inc would then map accordingly, but I am clearly missing something? How can I map any requests to /inc to the correct corresponding path?

Deploy ActionCable on Heroku (Rails 5 beta4)

Posted: 02 May 2016 03:40 AM PDT

I have a working rails 5 app with ActionCable on my localhost, and I'm trying to deploy it to heroku. When accessing the page where the chat room is, I can see in chrome's console:

WebSocket connection to 'wss://full-beyond-9816.herokuapp.com/cable' failed: Error during WebSocket handshake: Unexpected response code: 404  

I did setup Redis and the Redis addon on heroku. Here is the production part of my cable.yml file:

production: &production    :url: redis://redistogo:4140ce7f3e7493bd1b12@porgy.redistogo.com:9463/    :host: tarpon.redistogo.com    :port: 10272    :password: 12e348ac10ca002879ce7d85daf0bb0    :inline: true    :timeout: 1  

Here is my room.coffee file:

(function() {    this.App || (this.App = {});      App.cable = ActionCable.createConsumer();    }).call(this);  

Setting up ActionCable on heroku seems tricky, and every post I've found on the subject is either using Phusion Passenger (I'm using Puma), or with a pretty old version of ActionCable (I'm using the latest beta of Rails 5).

How should I set this up ? Thanks for your time and help

Rails: Validates greater_than_or_equal_to 0 does not work

Posted: 02 May 2016 03:47 AM PDT

I shouldn't be able to set user.fee_email = -1 but I can, even though I've specified in my model that the numericality of fee_email should be positive.

Given:

class User < ActiveRecord::Base    validates :fee_email, numericality: { greater_than_or_equal_to: 0 }  ...  end  

This should not happen:

2.2.1 :002 > a = User.first  2.2.1 :003 > a.fee_email   => #<BigDecimal:43cbbe0,'0.0',9(27)>   2.2.1 :004 > a.fee_email = -1   => -1   2.2.1 :005 > a.fee_email   => #<BigDecimal:43b5688,'-0.1E1',9(27)>   

Devise email templates [on hold]

Posted: 02 May 2016 05:15 AM PDT

I'm working with Devise in Ruby on Rails and I want to change defaul Devise email templates. I can't find .css files for email templates. Where should I put .css files for email templates?

Handling Confirmations of link by Custom Jquery Dialog in Rails

Posted: 02 May 2016 05:49 AM PDT

I needed a custom pop-up dialog in order to replace the default browser option for data-confirmation. There were a lot of example online for data-confirmation for method: delete, however I needed to make minor customization to make it work for normal links as well.

For example there are the 2 types of links I would render a dialog for:

<%= link_to(scoreboard_team_path(@scoreboard, team), remote: true, method: :delete, data: {confirm: "Are you sure you want to delete?"})%>     <%= link_to "Clear Teams", deleteteams_scoreboard_path(@scoreboard), class: "btn btn-primary reset-link", :data => {:confirm => "Are you absolutely sure you want to delete all teams?"} %>  

With the information I have researched online, I have come up with the following jquery code for app-wide confirmation for these types of links:

$(document).ready(function(){        $.rails.allowAction = function(link) {            if (!link.attr('data-confirm')) {              return true;            }            $.rails.showConfirmDialog(link);            return false;      };        $.rails.confirmed = function(link) {        link.removeAttr('data-confirm');        if(link.hasClass("reset-link")){           window.location.replace("" + link.context.href + "");        } else {            return link.trigger('click.rails');        }        };           $.rails.showConfirmDialog = function(link) {            var html;            var message = link.data("confirm");            html = "<div id=\"dialog-confirm\" title=\"Warning!\">\n  <p>"+message+"</p>\n</div>";            return $(html).dialog({              resizable: false,              modal: true,              buttons: {                OK: function() {                  $.rails.confirmed(link);                  return $(this).dialog("close");                },                Cancel: function() {                  return $(this).dialog("close");                }              }            });        };  });  

My problem is that the authors of the articles don't explain well about what is happening.

So therefore my questions are:

What does the following code mean:

if (!link.attr('data-confirm')) {              return true;            }  

In the line window.location.replace("" + link.context.href + ""); what does link.context.href mean?

Dotenv not availabe in routes.rb?

Posted: 02 May 2016 03:22 AM PDT

eversince I started using Dotenv inside my routes.rb I get weird errors.

I'm using gem 'dotenv-rails', '~> 2.0.0'

routes.rb:

constraints(host: ENV.fetch("SHORTENER_DOMAIN")) do    get ':id', to: 'shortener#redirect'  end  

Terminal:

username:~/Sites/my_app$ rails s  /Users/username/Sites/my_app/config/routes.rb:4:in 'fetch': key not found: "SHORTENER_DOMAIN" (KeyError)      from /Users/username/Sites/my_app/config/routes.rb:4:in 'block in <top (required)>'    username:~/Sites/my_app$ rails s  => Booting Thin  => Rails 4.2.5 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  => Ctrl-C to shutdown server  Thin web server (v1.6.4 codename Gob Bluth)  Maximum connections set to 1024  Listening on localhost:3000, CTRL+C to stop  

I did not do anything between these two rails s, just repeated it and it worked. It's really strange.

Anyone knows what's happening?

Sunday, May 1, 2016

Link in email to process an ics invitation | Fixed issues

Link in email to process an ics invitation | Fixed issues


Link in email to process an ics invitation

Posted: 01 May 2016 06:54 AM PDT

I have implemented an invitation system in my application, that generates an ical attachment that is sent to the appropriate users.

Is it possible to add a link in the email body that would trigger the processing of the invitation ? (in addition to the extra buttons provided by some email clients)

This question mentions that for email attachments in the general case it's not possible. Is it still the case for icalendar attachments ?

Other questions suggest using a service like https://www.addevent.com/, but this seems to be more oriented toward "public events", whereas in my case I would need something quite private (only invitations between 2 people), that are expected to be generates quite often (should be able to scale up to 100/day without problem), or it it just me getting a bad impression ?

Running rails with webrick in debian vm need domain

Posted: 01 May 2016 06:50 AM PDT

I'm running a debian vm and inside there, there runs my rails application on a webrick server.

the default domain is lvh.me .. it comes out of the box from webrick I thought. Is there I possibility to change the lvh.me? so that I can run two virtual machines on my desktop? and can acces one with lvh.me and the second one with blubb.me or something like that?

Cloudwatch metric data coming out empty

Posted: 01 May 2016 06:33 AM PDT

I am using the AWS Ruby SDK to programmatically setup an EMR cluster. And here I am trying to get the metrics for it :

cloudwatch = Aws::CloudWatch::Client.new  resp = cloudwatch.get_metric_statistics({        namespace: "AWS/ElasticMapReduce", # required        metric_name: "isIdle", # required        dimensions: [          {            name: "JobFlowId", # required            value: "j-3E3C10DQ0916E", # required          },        ],        start_time: Time.now - 3600, # required        end_time: Time.now, # required        period: 60, # required        statistics: ["SampleCount"], # required, accepts SampleCount, Average, Sum, Minimum, Maximum        unit: "Seconds", # accepts Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None      })  

But the thing is, the response I get is empty

#<struct Aws::CloudWatch::Types::GetMetricStatisticsOutput   label="isIdle",   datapoints=[]>  

Am I doing something wrong here?

what is the way to deploy rails apps in digital ocean through windows laptop?

Posted: 01 May 2016 06:21 AM PDT

since digital ocean is linux-based and i'm using a windows laptop, the only way to deploy rails apps is using VM to boot Ubuntu OS and deploy from there?

How do I param the Controller Favorite Create method to have an index#view

Posted: 01 May 2016 06:18 AM PDT

I want to create a polymorph model to favorite each object I want to create to stock in my user page. I am developing a web app to learn japanese and we can favorite different types of cards as kanas or kanjis and sentences. So there are 3 objects and soon more to favorite.

I migrated a table which names Favorite :

  create_table "favorites", force: :cascade do |t|      t.integer  "user_id"      t.integer  "favoritable_id"      t.string   "favoritable_type"      t.datetime "created_at",       null: false      t.datetime "updated_at",       null: false    end  

Here is the Favorite model belongs_to

class Favorite < ActiveRecord::Base    belongs_to :favoritable, polymorphic: true    belongs_to :user  end  

Here are the Cards model has_many

class Symbole < ActiveRecord::Base      accepts_nested_attributes_for :kanji_attribute, :allow_destroy => true    has_many :sentence_symboles, :class_name => "SentenceSymbole", :foreign_key => "symbole_id"    has_many :favorites, as: :favoritable       end  

and I added in sentence model too

class Sentence < ActiveRecord::Base      include Authority::Abilities      has_many :sentence_symboles, :class_name => "SentenceSymbole", :foreign_key => "sentence_id", dependent: :destroy      has_many :favorites, as: :favoritable  end  

Now here is the Favorite controller and I don't really know how to write the create method. Here is the Controller I do:

class FavoritesController < ApplicationController    def index       @favorites = Favorite.where(user: current_user)    end      def create      #Favorite.create(user_id: User.last.id, favoritable_id: Symbole.last.id, favoritable_type:"Symbole")      @favorite = current_user.favoritable.favorites.create(symbole: @symbole, sentence: @sentence).first      if @favorite.present?         @favorite.destroy      else        @favorite = current_user.favorites.new(symbole: @symbole, sentence: @sentence)        if not @symbole.favorites.where(user: current_user).take            @sentence.favorites.where(user: current_user).take            @favorite.save        end      end      # redirect_to favs_path      # redirect_to :back      respond_to do |format|        format.js { render :ajax_update_favs }      end    end      def destroy      @favorite = Favorite.find(params[:id])      @favorite.destroy      redirect_to :back    end  end  

Please could someone give me the right way to favorite all object I want and add in an favorite index#view.

Thank you for your help.

How can I add a large number of static HTML files to rails app without slowing the development cycle?

Posted: 01 May 2016 06:17 AM PDT

I am wondering the best way to include an old web site into a newer rails app.

The legacy web site:

  • Has 21,000 small text files with minimal markup that are linked together.
  • Totals ~ 220MB
  • Has a root page located within a directory and is linked to many sub-directories

I'd like to include the old site in my rails app folder, but I am concerned that it will mean a much longer development cycle each time I deploy. I am using capistrano and my first thought is to place the folder with Old Site in the shared directory on the production server and symbolically link to it accordingly. This approach strikes me as undesirable as my resources for New App will be split in more than one location. The benefit might be a much quicker debug/deploy cycle.

Right now, I have no plans to modify the Old Site files. At some point, that could change.

I have been impressed with how quickly my otherwise lightweight project will deploy. Right now I am making frequent changes and repeating the code/deploy cycle often. I'd like to avoid slowing that down unnecessarily.

Is there a best practice for this sort of thing?

wrong number of arguments (1 for 0) in the View

Posted: 01 May 2016 05:49 AM PDT

I understand what wrong number of arguments (1 for 0) means, but I don't understand why I am getting it for this line of code: <% if current_user.try(:email) == Join.all(:email) %> I am getting the error on Join.all(:email) Basically, what I am trying to do is check to see if the current_user.try(:email) matches any of the email for Join.all The Join method is made up of strings that are :email. Here's what my table looks like

create_table "joins", force: :cascade do |t|      t.string   "email"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end  

Help is much appreciated.

Rails Assets Pipeline load JavaScript from controllers and methods

Posted: 01 May 2016 05:53 AM PDT

I want to stay DRY in my code so I want to auto-load my javascripts file when it matches a controller or/and a method and the .js exists. I added this to my layout

= javascript_include_tag params[:controller] if ::Rails.application.assets.find_asset("#{params[:controller]}.js")  = javascript_include_tag "#{params[:controller]}/#{params[:action]}" if ::Rails.application.assets.find_asset("#{params[:controller]}/#{params[:action]}.js")  

So now when I add javascripts/my_controller/my_method.js it automatically loads it, which's nice.

Sadly I must add another line to precompile the asset otherwise an error is thrown (which says I must precompile my .js file) and I didn't find any way around this.

Rails.application.config.assets.precompile += %w( orders/checkout.js )  

Does anyone has a solution to avoid tu add manually elements in this configuration ?

NOTE : I already tried to use require_tree . which was just loading all the files on every page and was not working in my case.

serialize a column and save

Posted: 01 May 2016 06:49 AM PDT

I'm using rails 4.2 with ruby 2.2. I'm trying to save some data inside a column in a hash format.

I'm trying to save license details in the license column which is of text datatype, and in the respective model i've given:

serialize :license, JSON  

I have this in the controller:

params.require(:company_detail).permit(:company_name, :trading_name, :contact_name, :acn, :address, :suburb, :state, :post_code, :phone_number, :fax_number, :nrma_approved, :start_date, :release_date , :website_url ,:email, license: {date1: :date1, license1: :license1, date2: :date2, license2: :license2, date3: :date3, license3: :license3, date4: :date4, license4: :license4})  

and in form

= form_for @company_detail, remote: true, html: {class: 'form-horizontal form-label-left', data: {"parsley-validate" => ""}} do |f|        = f.fields_for :license do |l|          .row            .col-lg-6              .form-group                %label.control-label.col-md-4.col-xs-12 Date 1                .col-md-8.col-xs-12                  = l.text_field :date1, value: @company_detail.license.present? ? @company_detail.license["date1"] : '', class: 'date-picker form-control has-feedback-left datePicker'            .col-lg-6              .form-group                %label.control-label.col-md-4.col-xs-12 Licence Number 1                .col-md-8.col-xs-12                  = l.text_field :license1, value: @company_detail.license.present? ? @company_detail.license["license1"] : '', class: 'form-control'  

I tried entering a few fields in the form and submit, but even though the params are going in correctly, the value saved is null. This is the log:

Parameters: {"utf8"=>"✓", "company_detail"=>{"license"=>{"date1"=>"121212", "license1"=>"12313", "date2"=>"122131123", "license2"=>"123123", "date3"=>"", "license3"=>"", "date4"=>"", "license4"=>""}}, "commit"=>"Save", "id"=>"1"}  CompanyDetail Load (0.3ms)  SELECT  "company_details".* FROM "company_details" WHERE "company_details"."id" = $1 LIMIT 1  [["id", 1]]   User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]   (1.0ms)  BEGIN  SQL (0.4ms)  UPDATE "company_details" SET "license" = $1, "updated_at" = $2 WHERE "company_details"."id" = $3  [["license", "{\"date1\":null,\"license1\":null,\"date2\":null,\"license2\":null,\"date3\":null,\"license3\":null,\"date4\":null,\"license4\":null}"], ["updated_at", "2016-05-01 12:15:44.918547"], ["id", 1]]  

Issue in JQuery Validation with AngularJS

Posted: 01 May 2016 04:37 AM PDT

I use ruby on rails and Angular.

I follow - https://github.com/jpkleemans/angular-validate

I do following

APPLICATION.JS

//= require jquery  //= require app/jquery.validate.min.js  //= require angular  //= require app/angular-validate  //= require angular-resource  //= require ui-bootstrap  //= require ui-bootstrap-tpls  //= require app/assets  //= require app/services  //= require app/filters  //= require app/directives  // require app/showErrors.js  //= require app/controllers  //= require app/security  //= require app/app  //= require app/services/UserService.js  //= require app/services/FlashService.js  //= require app/cookie.js  

APP.JS

var app;  app = angular.module('app', [    'ui.bootstrap',     'security',    'app.services',     'app.controllers',     'app.filters',     'app.directives',    'ngCookies',    'ngValidate'    //'ui.bootstrap.showErrors'  ]);  app.constant('config', 'http://localhost:3000/api/v1')      app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {      $locationProvider.html5Mode(true);    $routeProvider.      when('/signup', {      controller: 'LoginCtrl',      templateUrl: ASSETS['signup']    }).    when('/login', {      controller: 'LoginCtrl',      templateUrl: ASSETS['login']    }).    when('/logout', {      controller: 'LoginCtrl',        }).    otherwise({      redirectTo:'/'    });  }]);    angular.module('app').run(['$rootScope', '$location', 'UserService', '$cookieStore', '$http', 'security', function($rootScope, $location, UserService, $cookieStore, $http, security) {      $rootScope.globals = $cookieStore.get('globals') || {};      if ($rootScope.globals.currentUser) {      $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata;     }      $rootScope.$on('$locationChangeStart', function (event, next, current) {        var restrictedPage = $.inArray($location.path(), ['/info', '/signup', '/login']) === -1;      var loggedIn = $rootScope.globals.currentUser;        if (restrictedPage && !loggedIn) {        $location.path('/login');      }    });    }]);    app.config(function($httpProvider) {    $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');      var interceptor = ['$rootScope', '$q', function(scope, $q) {      function success( response ) {        return response      };        function error( response ) {        if ( response.status == 401) {          var deferred = $q.defer();          scope.$broadcast('event:unauthorized');          return deferred.promise;        };        return $q.reject( response );      };      return function( promise ) {        return promise.then( success, error );      };    }];      $httpProvider.responseInterceptors.push( interceptor );  });  

LoginCtril

window.LoginCtrl = ['$scope', '$http', '$location', 'UserService', 'FlashService', 'config', 'security', function($scope, $http, $location, UserService, FlashService, config, security) {      // Signup     $scope.signup = function(){            $scope.loginProcess = true;          UserService.Signup($scope.user, function(response){              if (response.success){            UserService.SetCredentials(response.access_token);                  $location.path('/login')              }else{            $scope.authError = response.errors            FlashService.Error(response.errors);              }          $scope.loginProcess = false;          })    };      $scope.validationOptions = {      rules: {          firstname: {              required: true,          },      },      messages: {          firstname: {              required: "This field is required.",          },      }    }      }];  

and This is my Form.

<div data-ng-controller="LoginCtrl">  {{validationOptions}}    <div ng-class="{ 'alert': flash, 'alert-success': flash.type == 'success', 'alert-danger': flash.type == 'error' }" ng-if="flash" ng-bind="flash.message"></div>    <form name ='signupForm' data-ng-submit="signupForm.$valid && signup()" novalidate ng-validate="validationOptions">    <div class="form-group">      <label>First Name</label>        <input type="text" name="firstname" class="form-control" ng-model="user.firstname" required />    </div>      <button type="submit" class="btn btn-primary" ng-click="submitted=true">Submit</button>    </form>    </div>  

The Jquery validation is not display what wrong with above code please help me. Thank You.

deploy rails app using capistrano or aws opsworks?

Posted: 01 May 2016 04:04 AM PDT

I have written a twilio app that I would like to deploy on AWS. This is my first time and I find two options which I would like ask about. Should I deploy my app to aws using

1) AWS Opsworks? Link or

2) Capistrano Link

Hoping to simply get some direction, I am very new to this.

Combine Ruby on Rails and AngularJS

Posted: 01 May 2016 03:46 AM PDT

Maybe this is a dumb question or even a common asked question (or just a lousy searcher). I want to start a new web application project using Ruby on Rails. On the other hand, I really like Angular JS with Angular Material for the form design. The have everything already implemented like an autocomplete, different types of buttons, etc.

Now the question is, how to combine those two? I want to use Ruby on Rails's routing, controller, models, resource etc. but Angular Material more for the Frontend Design and catch user's actions in events.

Rails: Missing required arguments: aws_access_key_id, aws_secret_access_key (ArgumentError)

Posted: 01 May 2016 04:10 AM PDT

This error has been asked about before but I have tried all the answers on here and none have worked.

I am trying to connect AWS s3 to rails:

and I am getting the error pasted at the bottom of this question.

carrierwave.rb:

CarrierWave.configure do |config|    config.fog_provider = 'fog/aws'                        # required    config.fog_credentials = {      provider:               'AWS',                        # required      aws_access_key_id:      ENV['AWS_ACCESS_KEY_ID'],     # required      aws_secret_access_key:  ENV['AWS_SECRET_ACCESS_KEY'], # required      region:                 ENV['AWS_REGION'],            # optional, defaults to 'us-east-1'      }    config.fog_directory  = 'discoveredfmyelpdemo'                          # required    config.fog_public     = false                                        # optional, defaults to true    config.fog_attributes = { 'Cache-Control' => "max-age=#{365.day.to_i}" } # optional, defaults to {}  end  

I used figaro for my environmental vaiables which installed successfully and created application.yml (Note hashes are to cover up key but are correct in file):

AWS_ACCESS_KEY_ID: "A########################SA"  AWS_SECRET_ACCESS_KEY: "ba####################st"  AWS_REGION: "Sydney"  development:      AWS_BUCKET: discoveredfmyelpdemo  production:      AWS_BUCKET: discoveredfmyelpdemo  

I don't know why this should affect it but just in case I will give you my gem and uploader relevant file contents (I am new to ROR).

Avatar_Uploader.rb:

class AvatarUploader < CarrierWave::Uploader::Base      def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end  end  

Gemfile:

gem "fog-aws"  gem 'carrierwave', github: 'carrierwaveuploader/carrierwave'  gem 'figaro', '1.0'  

and this is the full error:

=> Booting WEBrick  => Rails 4.2.5 application starting in development on http://0.0.0.0:8080  => Run `rails server -h` for more startup options  => Ctrl-C to shutdown server  Exiting  /usr/local/rvm/gems/ruby-2.3.0/gems/fog-core-1.38.0/lib/fog/core/service.rb:244:in `validate_options': Missing required arguments: aws_access_key_id, aws_secret_access_key (ArgumentError)          from /usr/local/rvm/gems/ruby-2.3.0/gems/fog-core-1.38.0/lib/fog/core/service.rb:268:in `handle_settings'          from /usr/local/rvm/gems/ruby-2.3.0/gems/fog-core-1.38.0/lib/fog/core/service.rb:98:in `new'          from /usr/local/rvm/gems/ruby-2.3.0/gems/fog-core-1.38.0/lib/fog/core/services_mixin.rb:16:in `new'          from /usr/local/rvm/gems/ruby-2.3.0/gems/fog-core-1.38.0/lib/fog/storage.rb:27:in `new'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/carrierwave-98d73a935047/lib/carrierwave/uploader/configuration.rb:123:in `eager_load_fog'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/carrierwave-98d73a935047/lib/carrierwave/uploader/configuration.rb:136:in `fog_credentials='          from /home/ubuntu/workspace/config/initializers/fog.rb:2:in `block in <top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/carrierwave-98d73a935047/lib/carrierwave/uploader/configuration.rb:158:in `configure'          from /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/carrierwave-98d73a935047/lib/carrierwave.rb:14:in `configure'          from /home/ubuntu/workspace/config/initializers/fog.rb:1:in `<top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `load'          from /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `block in load'          from /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:240:in `load_dependency'          from /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in `load'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:652:in `block in load_config_initializer'          from /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.5/lib/active_support/notifications.rb:166:in `instrument'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:651:in `load_config_initializer'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:615:in `each'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:615:in `block in <class:Engine>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:30:in `instance_exec'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:30:in `run'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:55:in `block in run_initializers'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:44:in `each'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:44:in `tsort_each_child'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:415:in `call'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `call'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'          from /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:54:in `run_initializers'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/application.rb:352:in `initialize!'          from /home/ubuntu/workspace/config/environment.rb:5:in `<top (required)>'          from /home/ubuntu/workspace/config.ru:3:in `require'          from /home/ubuntu/workspace/config.ru:3:in `block in <main>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `instance_eval'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `initialize'          from /home/ubuntu/workspace/config.ru:in `new'          from /home/ubuntu/workspace/config.ru:in `<main>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `eval'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `new_from_string'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:40:in `parse_file'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/server.rb:299:in `build_app_and_options_from_config'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/server.rb:208:in `app'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/server.rb:61:in `app'          from /usr/local/rvm/gems/ruby-2.3.0/gems/rack-1.6.4/lib/rack/server.rb:336:in `wrapped_app'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/server.rb:139:in `log_to_stdout'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/server.rb:78:in `start'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:80:in `block in server'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:75:in `tap'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:75:in `server'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.5/lib/rails/commands.rb:17:in `<top (required)>'          from /home/ubuntu/workspace/bin/rails:9:in `require'          from /home/ubuntu/workspace/bin/rails:9:in `<top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `load'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `call'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.1/lib/spring/client/command.rb:7:in `call'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.1/lib/spring/client.rb:30:in `run'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.1/bin/spring:49:in `<top (required)>'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `load'          from /usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `<top (required)>'          from /home/ubuntu/workspace/bin/spring:13:in `require'          from /home/ubuntu/workspace/bin/spring:13:in `<top (required)>'          from bin/rails:3:in `load'          from bin/rails:3:in `<main>'  

Thanks for your help.

Sum of all amount if created_at dates are the same in Rails

Posted: 01 May 2016 05:28 AM PDT

I'm trying to replicate this with the Rails database (pg) query but not having much luck.

My Foo table has many columns but I'm interested in created_at and amount.

Foo.all.where(client_id: 4) looks like this:

[    [0] {:created_at => <date>, :amount => 20},    [1] {:created_at => <different date>, :amount => 5},    ...  ]  

Stripe Charge Object is in json so I thought I could:

f = Foo.all.where(client_id: 4).as_json # could I?  

Anyhow, my controller:

# As per first link above  def each_user_foo    starting_after = nil    loop do      f = Foo.all.where(client_id: 4).as_json      #f_hash = Hash[f.each_slice(2).to_a] # I was trying something here      break if f.none?      f.each do |bar|        yield bar      end      starting_after = bar.last.id    end  end    foo_by_date = Hash.new(0)    each_user_foo do |f|    # Parses date object. `to_date` converts a DateTime object to a date (daily resolution).    amount_date = DateTime.strptime(f.created_at.to_s, "%s").to_date # line 50    amount = f.amount      # Initialize the amount for this date to 0.    foo_by_date[amount_date] ||= 0      foo_by_date[amount_date] += amount  end  

My error at line 50 is:

undefined method `created_at' for Hash

I guess an object is still in an array somewhere. Also, is there an equivalent for the JS console.log() in Rails? Would be handy.

Rails FactoryGirl inside app in development env

Posted: 01 May 2016 05:13 AM PDT

I'm trying to use FactoryGirl gem inside my App in development mode (it's for mailer tests more) with rails_email_preview gem.

It works but only on initial page load, after reloading/refreshing the page I get following error:

Factory not registered: order  

where order is name of factory.

Here is my code (it is a dummy app for my Rails Engine):

spec/dummy/app/mailer_previews/mymodule/order_mailer_preview.rb

Dir[Mymodule::Core::Engine.root.join('spec', 'factories', '*')].each do |f|    require_dependency f  end    module Mymodule  class OrderMailerPreview    def confirmation_email        o = FactoryGirl.create(:order)        OrderMailer.confirmation_email(o)    end  end  end  

Of course my factories works without any problem in test environment.

Any help would be appreciated.

EDIT:

p FactoryGirl.factories  

returns (after page reload)

#<FactoryGirl::Registry:0x007ff2c9dd29d0 @name="Factory", @items={}>  

Rails - Bootstrap popover js

Posted: 01 May 2016 02:14 AM PDT

Im trying to understand how js works in Rails.

I am using bootstrap and have managed to get popovers working, but not in the way that i had understood Rails works.

I currently have a partial called _preferences inside my organisations views folder. In my organisations show page, I render that partial. The partial has a button which calls a popover, as:

 <button class="fa fa-info-circle fa-2x fa-border btn-info" id="publicity" href="#"  rel="popover" data-original-title="Publicity Issues" data-content="<%= publicity_popover(@organisation.preference)%>"></button>  

I tried to make an organisations.js file that had:

$('#publicity').popover()  $('#academic_publication').popover()  $('#presentations').popover()  

but the popovers didn't work when I tried that approach.

When I add the following to the bottom of the preferences partial, it all works fine.

<script>  $('#publicity').popover()  $('#academic_publication').popover()  $('#presentations').popover()  </script>  

I expected the first attempt to work. I can't understand why it doesnt. Does any one see the error?

Making image url link only with plain text using auto_html Gem

Posted: 01 May 2016 06:49 AM PDT

I put the following text and got an unexpected result using the bundled image filter (AutoHtml::Image).

<img src="http://hoge/image.png">  

That filter translated it into the followging code.

<img src=""  <a href="http://hoge/image.png">    <img src="http://hoge/image.jpg">  </a>  "">  

I just wanted to transralte only with plain text not with html tag.

How can I solve that problem?

How do you remove an actioncable channel subscription in Rails 5 with App.cable.subscriptions.remove?

Posted: 01 May 2016 12:21 AM PDT

To create subscriptions I run:

  App.room = App.cable.subscriptions.create({      channel: "RoomChannel",      roomId: roomId    }, {      connected: function() {},      disconnected: function() {},      received: function(data) {        return $('#messages').append(data['message']);      },      speak: function(message, roomId) {        return this.perform('speak', {          message: message,          roomId: roomId        });      }    });  

But because I want the client to never be subscribed to more than one channel, what can I run each time before this to remove all subscriptions the client has?

I tried to do something super hacky like:

App.cable.subscriptions['subscriptions'] = [App.cable.subscriptions['subscriptions'][1, 0]]  

But I'm sure it didn't work because there are many other components that go into a subscription/unsubscription.

App.cable.subscriptions.remove requires a subscription argument, but what do I pass in?

Thanks!

How to create a record from the belongs_to association?

Posted: 01 May 2016 12:42 AM PDT

I have this association:

user.rb

class User < ActiveRecord::Base    has_many :todo_lists  end  

todo_list.rb

class TodoList < ActiveRecord::Base    belongs_to :user  end  

And I'm trying to understand the following behavior:

todo_list = TodoList.create(name: "list 1")    todo_list.create_user(username: "foo")    todo_list.user  #<User id: 1, username: "foo", created_at: "2016-05-01 07:09:05", updated_at: "2016-05-01 07:09:05">    test_user = todo_list.user    test_user.todo_lists # returns an empty list  => #<ActiveRecord::Associations::CollectionProxy []>    test_user.todo_lists.create(name: "list 2")    test_user.todo_lists  => #<ActiveRecord::Associations::CollectionProxy [#<TodoList id: 2, name: "list 2", user_id: 1, created_at: "2016-05-01 07:15:13", updated_at: "2016-05-01 07:15:13">]>  

Why #create_user adds user to todo_list (todo_list.user returns the user), but does not reflect the association when user.todo_lists is called?

Using a remote Postgresql with AWS for Rails app

Posted: 30 Apr 2016 11:57 PM PDT


Need urgent help.
I am using a remote POSTGRESQL on another server and want to deploy rails app to AWS. I want the AWS to communicate with that remote POSTGRESQL DB server.
I'm getting the error

FATAL: Peer authentication failed for user "postgres"

Although I've whitelisted the IP in pg_hba.conf

How I've whitelisted?

I've seen the Public IP in AWS Console and added that.
I've pinged my AWS site and added that IP
Any tutorials?
Thanks in advance

Rails need help in devise signup using only email [on hold]

Posted: 01 May 2016 02:19 AM PDT

I am using rails 4 and devise 3. I want to allow user to sign-up using email only. After sign-up a mail should be sent with a link to set the password. Please let me know how to do this.

How can I implement in Rails bid offers that sellers can cancel or accept within 24hrs or transaction is cancelled?

Posted: 01 May 2016 12:00 AM PDT

I am working on a marketplace in rails that allows buyers to make an offer to the seller as a bid for a product. The seller can cancel or accept the bid but only has a 24 hr window to do this or the bid expires and the transaction is cancelled. How can the transaction for bids be implemented. The hardest part is actually figuring out creating the timer in rails. I also thought about some sort of boolean functionality to inform the seller if the bid status is pending or cancelled or accepted but that becomes three possible values that can not work in a true or false situation. Any help in any of these problems would be greatly appreciated.

rails multiple true in form submitting string

Posted: 30 Apr 2016 11:49 PM PDT

I am using rails4-autocomplete gem

In form I have

<%= form_for @group do |f| %>    <%= f.autocomplete_field :name, autocomplete_group_name_groups_path, 'data-delimiter' => ',', :multiple => true %>   <%= f.submit "Find" %>  <% end%>  

It is submitting params in the form of string, I want it in form of array.

Current params:

["NYC 1,NYC 2,"]  

I want

["NYC 1","NYC 2"]  

Please suggest

Rails 4 with will_paginate: How to make will_paginate not to escape html in content?

Posted: 30 Apr 2016 11:57 PM PDT

I want to extract posts using will_paginate. Inside the post content may contain <a href=''></a> tag for the reference link, so I don't want it to be escaped.

I have tried to add raw()

<%= raw will_paginate @posts %>

and use html_safe() for the content string before putting it to the database

params[:post][:content].html_safe  @post = @user.post.build(post_params)  

I would really appreciate any help. Thanks.

Rails 4 ToDo list, adding rows to the table

Posted: 30 Apr 2016 10:57 PM PDT

I am able to add tasks to my page, however only the first task is displayed in the table. The rest is added as regular, unformatted text.

Here is my home.html.erb

<%= content_for :title, "Home" %>  <h1>Things To Do</h1>    <div class="container" id="table-width">  <% if @tasks.empty? %>  <span>There are no tasks at the moment!</span>  <% else %>    <table class="table">      <thead>        <td>Task</td>        <td>Note</td>        <td>Created At</td>      </thead>      <tbody>        <% @tasks.each do |task| %>        <tr>        <td><%= task.title %></td>        <td><%= task.note %></td>        <td><%= task.created_at.strftime("%A,%B,%Y") %></td>        </tr>      </tbody>    </table>    <% end %>  <% end %>  <%= link_to "New Task", new_path, class: "btn btn-primary" %>  </div>  

And here is my new.html.erb

 <h1>Write your task here</h1>    <div>  <%= form_for(@task) do |f| %>  <div class="form-group">  <%= f.label :title %>  <%= f.text_field :title, class: "form-control" %>  </div>  <div class="form-group">  <%= f.label :note %>  <%= f.text_area :note, class:  "form-control" %>  </div>  </div>    <%= f.submit "Create Task", class: "btn btn-primary" %>  <% end %>  

RoR - Running Production of Application fails to load images from CSS

Posted: 01 May 2016 04:28 AM PDT

I have a rails application that works fine in development but can not get certain images that are loaded from css files to load. Images that are on the html.erb load fine though.

Here is the string in my css:

.greyscale .banner-logo {      background: url(/assets/theme/greyscale/greyscale_main_logo.png) no-repeat center center;  }  

Here is my production.rb (with comments removed):

Rails.application.configure do    config.cache_classes = true    config.eager_load = true    config.consider_all_requests_local       = false    config.action_controller.perform_caching = true    config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?    config.assets.js_compressor = :uglifier    config.assets.compile = false    config.assets.digest = true    config.log_level = :debug    config.i18n.fallbacks = true    config.active_support.deprecation = :notify    config.log_formatter = ::Logger::Formatter.new    config.active_record.dump_schema_after_migration = false  end  

and here is my development.rb (with comments removed):

Rails.application.configure do    config.cache_classes = false    config.eager_load = false    config.consider_all_requests_local       = true    config.action_controller.perform_caching = false    config.action_mailer.raise_delivery_errors = false    config.active_support.deprecation = :log    config.active_record.migration_error = :page_load    config.assets.debug = true    config.assets.digest = true    config.assets.raise_runtime_errors = true  end  

and here is my assets.rb:

Rails.application.config.assets.version = '1.0'  Rails.application.config.assets.precompile += [/.*\.js/,/.*\.css/]  

What do I need to add/modify in my production.rb to allow me to view images from css files?

Ajax Request with Rails 5 App getting error 422 (Unprocessable Entity)

Posted: 30 Apr 2016 10:50 PM PDT

I'm getting a 422 (Unprocessable Entity) error when I try to click upvote on my Rails 5 app. What I'm simply trying to do is post the vote (or like) to the page. My Ajax request

"use strict";  console.log("loaded");  $(document).ready(function(){    $("#upvote").click(function() {  console.log("clicked");  var id = $(this).data("id");  $.ajax({     url: "/movies/votes",    type: "POST",    data: {      id: id,   votes: true    },    success: function() {      var vote_counter = $("#votes");      // console.log(vote_counter);      var current_vote = parseInt($("#votes").html());      vote_counter.html(current_vote + 1);      //alert(vote_counter);        }       })     })    })  

Controller

def votes   @movie.update(votes: @movie.votes + 1)  end  

I have another app where I used a similar request and it works fine, but not here. Not sure where I'm going wrong on this one. Sidenote, I disabled turbolinks for now because that has been the issue in the past. If needed, here's my GitHub

How to run a command automatically after each reboot

Posted: 30 Apr 2016 10:15 PM PDT

I currently have Ubuntu 16.04 installed on my virtual box. I installed Ruby and Rails by RVM. After that I tried

$ rails  

The terminal said

The program `rails` is currently not installed. You can install it by typing:   sudo apt install ruby-railties  

I solve this problem by typing

$ source ~/.rvm/scripts/rvm  

Credits here

However, once I reboot the virtual machine, everything I did with source will lose and I need to re-enter

 $ source ~/.rvm/scripts/rvm  

I also have some similar cases I need to do on every reboot. So is there any solution can make those command be run automatically each time?

There was an error while trying to load the gem 'sass-rails'. (Bundler::GemRequireError)

Posted: 30 Apr 2016 09:41 PM PDT

I am getting an error while starting rails server.

C:\Ruby22-x64\WebAppRails>rails s C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'sass-rails'. (Bundler::GemRequireError)          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'          from C:/Ruby22-x64/WebAppRails/config/application.rb:7:in `<top (required)>'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `require'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:78:in `block in server'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `tap'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `server'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'          from bin/rails:4:in `require'          from bin/rails:4:in `<main>'  

Here are the gems I'm using:

C:\Ruby22-x64\WebAppRails>bundle show  

Gems included by the bundle:

  • actionmailer (4.2.6)
  • actionpack (4.2.6)
  • actionview (4.2.6)
  • activejob (4.2.6)
  • activemodel (4.2.6)
  • activerecord (4.2.6)
  • activesupport (4.2.6)
  • arel (6.0.3)
  • binding_of_caller (0.7.2)
  • builder (3.2.2)
  • bundler (1.11.2)
  • byebug (8.2.5)
  • coffee-rails (4.1.1)
  • coffee-script (2.4.1)
  • coffee-script-source (1.10.0)
  • concurrent-ruby (1.0.1)
  • debug_inspector (0.0.2)
  • erubis (2.7.0)
  • execjs (2.6.0)
  • globalid (0.3.6)
  • i18n (0.7.0)
  • jbuilder (2.4.1)
  • jquery-rails (4.1.1)
  • json (1.8.3)
  • loofah (2.0.3)
  • mail (2.6.4)
  • mime-types (3.0)
  • mime-types-data (3.2016.0221)
  • mini_portile2 (2.0.0)
  • minitest (5.8.4)
  • multi_json (1.11.3)
  • nokogiri (1.6.7.2)
  • rack (1.6.4)
  • rack-test (0.6.3)
  • rails (4.2.6)
  • rails-deprecated_sanitizer (1.0.3)
  • rails-dom-testing (1.0.7)
  • rails-html-sanitizer (1.0.3)
  • railties (4.2.6)
  • rake (11.1.2)
  • rdoc (4.2.2)
  • sass (3.4.22)
  • sass-rails (5.0.4)
  • sdoc (0.4.1)
  • sprockets (3.6.0)
  • sprockets-rails (3.0.4)
  • sqlite3 (1.3.11)
  • thor (0.19.1)
  • thread_safe (0.3.5)
  • tilt (2.0.2)
  • turbolinks (2.5.3)
  • tzinfo (1.2.2)
  • tzinfo-data (1.2016.4)
  • uglifier (3.0.0)
  • web-console (2.3.0)

gem version is 2.4.5.1 and ruby version is 2.2.4

What do I need to do to fix this?

Error : 'incompatible library version' sqlite3-1.3.11 in rails

Posted: 01 May 2016 12:53 AM PDT

I working on Ubuntu system(16.04).

My problem is whenever i setup any rails project and try to run rails s then i got 'incompatible library version' error for sqlite3 something like below.

/home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/activesupport-4.0.0/lib/active_support/values/time_zone.rb:282: warning: circular argument reference - now  /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/sqlite3-1.3.11/lib/sqlite3.rb:6:in `require': incompatible library version - /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/sqlite3-1.3.11/lib/sqlite3/sqlite3_native.so (LoadError)      from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/sqlite3-1.3.11/lib/sqlite3.rb:6:in `rescue in <top (required)>'      from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/sqlite3-1.3.11/lib/sqlite3.rb:2:in `<top (required)>'      from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:77:in `require'      from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:77:in `block (2 levels) in require'      from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:72:in `each'      from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:72:in `block in require'      from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:61:in `each'      from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:61:in `require'      from /usr/lib/ruby/vendor_ruby/bundler.rb:99:in `require'      from /home/jiggs/sites/albumriverfinal/config/application.rb:7:in `<top (required)>'      from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/railties-4.0.0/lib/rails/commands.rb:76:in `require'      from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/railties-4.0.0/lib/rails/commands.rb:76:in `block in <top (required)>'      from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/railties-4.0.0/lib/rails/commands.rb:73:in `tap'      from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/railties-4.0.0/lib/rails/commands.rb:73:in `<top (required)>'      from bin/rails:4:in `require'      from bin/rails:4:in `<main>'  

Rails version : 4.0.0

ruby version i tried with rails 4.0.0 :

  • ruby-2.0.0-p247 [ x86_64 ]

  • ruby-2.2.5 [ x86_64 ]

  • ruby-2.3.0 [ x86_64 ]

  • ruby-2.3.0-preview1 [ x86_64 ]

  • ruby-2.3.1 [ x86_64 ]

I trying to uninstall sqlite3 using gem uninstall sqlite3 and trying to run bundle install but got this error :

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

Then i run gem install sqlite3 -v '1.3.11' and run rails server and got same error again incompatible library version.