Tuesday, May 3, 2016

Return records in an unusual offset order | Fixed issues

Return records in an unusual offset order | Fixed issues


Return records in an unusual offset order

Posted: 03 May 2016 07:03 AM PDT

Currently I have a scope that pulls back my records in the following standard order:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  

and it is converted in to a html block that's laid out as so:

1 2 3 4  5 6 7 8  9 10 11 12  13 14 15 16  

I want a html block that's laid out like so:

1 6 11 16  2 7 12   3 8 13  4 9 14  5 10 15  

So I think I need to pull the records back in the following order - (records offset by the number of rows)

1 6 11 16 2 7 12 3 8 13 4 9 14 5 10 15  

Any idea what is the neatest way to do this in Rails / ActiveRecord?

low-level caching key in rails. Built-in?

Posted: 03 May 2016 07:00 AM PDT

I'm reading the docs for Caching with Rails and I came across this:

Consider the following example. An application has a Product model with an instance method that looks up the product's price on a competing website. The data returned by this method would be perfect for low-level caching:

class Product < ApplicationRecord

def competing_price  >     Rails.cache.fetch("#{cache_key}/competing_price", expires_in: 12.hours) do  >       Competitor::API.find_price(id)  >     end   end end   

Notice that in this example we used the cache_key method, so the cache-key will be something like products/233-20140225082222765838000/competing_price. cache_key generates a string based on the model's id and updated_at attributes. This is a common convention and has the benefit of invalidating the cache whenever the product is updated. In general, when you use low-level caching for instance level information, you need to generate a cache key.

Do I need to build that cache_key method or is it built in? Would it just be something like this:

module ProductsHelper    def cache_key_for_products      count          = Product.count      max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)      "products/all-#{count}-#{max_updated_at}"    end  end  

Heroku deployment error RoR

Posted: 03 May 2016 07:01 AM PDT

When running my RoR app in Heroku shows this error:

We're sorry, but something went wrong.

If you are the application owner check the logs for more information.

Checking the heroku logs, this shows http://pastebin.com/yTWtRMVD

My main page is https://salty-stream-26420.herokuapp.com/ and my callback URL is https://salty-stream-26420.herokuapp.com/auth/twitter/callback in OmniAuth.

It runs in Cloud9 perfectly but not in Heroku. What is wrong?

Thank you, Alex.

How can I put a Postgres JSON value into a Rails fixture?

Posted: 03 May 2016 06:54 AM PDT

I just added a Postgres json type to a Rails/Active Record table I'm working with. I'd like to populate a record with a default value in Rails fixtures:

fixture_id:    existing_column: "foobar"    newly_added_column: <%= JSON.dump({:reason => 'foobar'}) %>  

Previously, I'd stored stringified JSON this way in a text column. However, when I now run this unit test:

test "my test" do    sut = fixtures(:fixture_id)    assert_not_nil sut.newly_added_column  end  

The test fails. Because it is JSON at the database level, I don't think it's useful to dump it to a string, but the YAML fixtures can't seem to keep an object as a Hash (when I try it without the JSON.dump, I get ActiveRecord::Fixture::FormatError: a YAML error occurred parsing).

Mind you, I am using Rails 3, so I think some of the support for this may be in Rails 4, but in Rails 3, the migration to add a json Postgres column type still work.

No route matches for inherited (create) action

Posted: 03 May 2016 06:59 AM PDT

I have 2 versions of my API(1&2) the controller of api version 2 inherits from the controller of api version 1. The problem is, specs for version 1 are running fine, but when i run specs in version 2, it tells me

ActionController::UrlGenerationError: No route matches {:action=>"create", :controller=>"api/mobile/v2/samples"}

#version 1  class Api::Mobile::V1::SamplesController < ApplicationController    def create     #dummy    end  end    #version 2  require "meta_data"  class Api::Mobile::V2::SamplesController < Api::Mobile::V1::SamplesController    include MetaData  end      #spec for version 1  require 'rails_helper'  RSpec.describe Api::Mobile::V1::SamplesController, type: :controller do    describe "POST #create" do      it "performs a post" do        post :create      end    end  end    #spec for version 2  require 'rails_helper'  RSpec.describe Api::Mobile::V2::SamplesController, type: :controller do    describe "POST #create" do      it "performs a post" do        post :create      end    end  end  

Rails redis cache storage size

Posted: 03 May 2016 06:46 AM PDT

I have rails app storing values to redis cache through a cron job overnight. But some values stored is showing as nil when I have checked in the morning. What is the storage size/limit of redis cache in rails? How can I change this value through configuration and runtime?

How to reading and Output [FILTERED] value from parameters in Ruby

Posted: 03 May 2016 06:45 AM PDT

I am using curl to post json to my example service. I am posting json to the service as shown below

curl \  > -i \  > -H "Accept: application/json" \  > -H "Content-type: application/json" \  > -X POST \  > -d '{"email":"micky@minn.com","full_names":"Inisne Dats", "password": "oasswn"}' http://localhost:3000/api/admin_users  

Below is my method thats responsible for creating and saving the new Active record Object

def create          user = AdminUser.new(white_list)              if user.save              head 200          else              puts user.errors.full_messages              head 500          end    end  

My Whitelist method below

private      def white_list          params.require(:admin_user).permit(:email,:full_names,:password)      end  

The problem is that this code never saves because the password is FILTERED, I have inspected the parameters and this is the output;

 {"email"=>"micky@minn.com", "full_names"=>"Inisne Dats", "password"=>"[FILTERED]", "admin_user"=>{"email"=>"micky@minn.com", "full_names"=>"Inisne Dats"}}  

Can anyone help show me how to retrieve the filtered password and use it once the parameters reach the controller method create. Or I'm I using whitelisting feature wrong?

Capistrano 3.5 deploy error 'database.yml' no such file or directory

Posted: 03 May 2016 06:42 AM PDT

Problems deploying to server since upgrading to Rails 4.2.6, Capistrano 3.5 and Ruby 2.3.1

It was fine with Rails 4.2.3, Capistrano 3.4 and Ruby 2.3.0.

It's failing on deleting database.yml and won't proceed with the linked files.

Capistrano nor deploy files have been changed.

Capistrano log:

DEBUG [d2eceac4] Command: [ -L /apps/rails.app/releases/20160503132540/config/database.yml ]   DEBUG [d23f79fc] Finished in 0.505 seconds with exit status 1 (failed).   DEBUG [8250d094] Running [ -f /apps/rails.app/releases/20160503132540/config/database.yml ] as deploy@10.1.1.1   DEBUG [8250d094] Command: [ -f /apps/rails.app/releases/20160503132540/config/database.yml ]   DEBUG [d2eceac4] Finished in 0.504 seconds with exit status 1 (failed).   DEBUG [57a5da20] Running [ -f /apps/rails.app/releases/20160503132540/config/database.yml ] as deploy@10.1.1.1   DEBUG [57a5da20] Command: [ -f /apps/rails.app/releases/20160503132540/config/database.yml ]   DEBUG [8250d094] Finished in 0.497 seconds with exit status 0 (successful).    INFO [57de892b] Running /usr/bin/env rm /apps/rails.app/releases/20160503132540/config/database.yml as deploy@10.1.1.1   DEBUG [57de892b] Command: ( export RBENV_ROOT="/home/deploy/.rbenv" RBENV_VERSION="2.3.1" ; /usr/bin/env rm /apps/rails.app/releases/20160503132540/config/database.yml )   DEBUG [57a5da20] Finished in 0.498 seconds with exit status 0 (successful).    INFO [db9b565c] Running /usr/bin/env rm /apps/rails.app/releases/20160503132540/config/database.yml as deploy@10.1.1.1   DEBUG [db9b565c] Command: ( export RBENV_ROOT="/home/deploy/.rbenv" RBENV_VERSION="2.3.1" ; /usr/bin/env rm /apps/rails.app/releases/20160503132540/config/database.yml )   DEBUG [57de892b]   rm:    DEBUG [57de892b]   cannot remove '/apps/rails.app/releases/20160503132540/config/database.yml'    INFO [db9b565c] Finished in 0.504 seconds with exit status 0 (successful).   DEBUG [57de892b]   : No such file or directory    INFO [3aaa1aef] Running /usr/bin/env ln -s /apps/rails.app/shared/config/database.yml /apps/rails.app/releases/20160503132540/config/database.yml as deploy@10.1.1.1   DEBUG [57de892b]      DEBUG [3aaa1aef] Command: ( export RBENV_ROOT="/home/deploy/.rbenv" RBENV_VERSION="2.3.1" ; /usr/bin/env ln -s /apps/rails.app/shared/config/database.yml /apps/rails.app/releases/20160503132540/config/database.yml )  

The Capistrano 'deploy.rb' file:

# config valid only for current version of Capistrano  lock '3.5.0'    set :application, 'rails.app'  set :repo_url, 'git@internal-address:user/rails-app.git'    # Passenger  set :passenger_restart_with_touch, true    # Default value for :linked_files is []  set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/secrets.yml', 'config/initializers/devise.rb', 'config/environments/production.rb')    # Default value for linked_dirs is []  set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system', 'public/uploads')    namespace :deploy do    after :publishing, :restart    after :finishing, :cleanup  end  

I'm not sure what how else to debug. The shared/config directory on the server has a database.yml file; also all symbolic links work eg. secrets.yml, devise.rb, production.rb

Any help is much appreciated.

rails app - mongoid not insert new field

Posted: 03 May 2016 06:43 AM PDT

I just started to create on app with rails-api and mongoDB (gem mongoid in rails).

I have created my model like this:

class User       include Mongoid::Document      include Mongoid::Timestamps        embeds_many :language      accepts_nested_attributes_for :language        field :name, type: String      field :lastname, type: String      field :mail, type: String      field :passwd, type: String      field :auth_token, type: String  end  

And i want to add another field in my model.

So at the end of my model i add this:

field :slug, type: String  

But when i insert a new document, mongoid doesn't detect the new field and return null.

I try to do rake:migration but is useless with mongodb and i can't find the issue. Could you help me?

Best regards

Sidekiq: pass an object as parameter

Posted: 03 May 2016 06:41 AM PDT

I have a sidekiq worker that connects to a remote odbc database, fetches the data and then update the local database. Now I'm splitting the worker into two workers. One will connect and fetch the data and another will update the records.

The connection returns an object #<OCI8::Cursor:0x00000007703f30> that I'm passing in parameters to the second worker.

SecondWorker.perform_async({:odbc => connection})  

In the second worker I tried to use it:

def perform(options)    order_odbc = options['odbc']  end  

But it treats the object as string

"#<OCI8::Cursor:0x00000006bddf48>":String  

Is there any other way to pass the objects in parameters?

Swap images and disabling buttons using Jquery

Posted: 03 May 2016 06:36 AM PDT

I'm using icons to create 6 separate buttons. Each button has an active and inactive state (two different images). How can I swap images when a button is active and disable any other button that was made active beforehand?

Here's a snippet of the JQuery code I'm using to swap the images

$(".img-swap").on('click', function() {      if ($(this).attr("class") == "img-swap") {        this.src = this.src.replace("_btn","_active");      } else {        this.src = this.src.replace("_active","_btn");      }      $(this).toggleClass("active");    });  });  

And here is a snippet of how my buttons are laid out in HTML/erb:

<button class="event-btn" disabled>      <%= link_to image_tag("example_btn.png", class: "img-swap"), "#"  %>  </button>  

Thank you very much in advance! I'm still learning and this will help tremendously!

Changing path for integration tests on a Paperclip Attachment

Posted: 03 May 2016 06:28 AM PDT

The documentation for Paperclip mentions that you can change the upload path for tests by placing the following code in the test.rb environment file:

Paperclip::Attachment.default_options[:path] = "#{Rails.root}/spec/test_files/:class/:id_partition/:style.:extension"  

The issue I'm having is that the Attachment has a path set in the model, that doesn't get overwritten:

has_attached_file :photo, path: ':attachment/:id/:style.:extension'  

When I'm running the tests the files get uploaded to the /photo/ folder instead of /spec/test_files/.

I can probably achieve this by writing a custom Paperclip adapter, but there must be an easier way.

Ruby on Rails - posts#show creates [ ] line

Posted: 03 May 2016 06:48 AM PDT

Here is my posts_controller.rb

class PostsController < ApplicationController      def index          @posts = Post.all.order("created_at DESC")      end        def new      end        def create          @post = Post.new(post_params)            @post.save          redirect_to @post      end        def show          @post = Post.find(params[:id])      end        private           def post_params              params.require(:post).permit(:title, :body)          end  end  

here is my index.html.erb

<%= @posts.each do |post| %>      <div class="post_wrapper">          <h2 class="title"><%= link_to post.title, post %></h2>          <p class="date"><%= post.created_at.strftime("%B, %d, %Y") %></p>      </div>  <% end %>  

Here's how the page looks like: screenshot

Why does that [ ] line show up ? How do I hide/delete it ?

Poltergeist capybara view testing taking long time when running all test in spec in ruby on rails

Posted: 03 May 2016 06:28 AM PDT

I'm using capybara with poltergeist for rspec testing in ruby on rails.

We're using stripe for payment gateway.

Request to stripe in already stub and real http connections are disabled.

However when I run the spec file alone.

It passes with the following test result.


Can add billing information to my account

Finished in 14.27 seconds (files took 4.84 seconds to load) 1 example, 0 failures


But when I run all the test it fails due to long time delay for response and I'm getting this output.

Failures:

enter image description here

My code-

scenario "Can add billing information to my account", js: true do      within "#top-menu" do        click_link "ACCOUNT"      end      click_link "Billing"        click_link "Add billing information"        within "#subscription" do        fill_in "Name", with: "John Smith"        fill_in "Email", with: "john.smith@example.com"        fill_in "Phone number", with: "0443 123123"        fill_in "Company", with: "Cribber"        fill_in "Street address", with: "14 Somewhere Street"        fill_in "City", with: "Brisbane"        fill_in "Postcode / Zip", with: "4000"        fill_in "State", with: "QLD"        select "Australia", from: "Country"        select "Australian Dollar", from: "Currency"          fill_in "Card number", with: "4242424242424242"        select Time.now.year + 1, from: "card_expiry_year"        fill_in "CVC", with: "123"          check "subscription_billing_attributes_terms_of_service"      end        click_button "Subscribe"      expect(page).to have_content("Thank you for subscribing to Cribber!")    end  

I added sleep(200) after click_button "Subscribe".But it showed the following result.

enter image description here

Can anyone please help?

Thanks in advance for helping.

Creating a correct query with joins

Posted: 03 May 2016 06:20 AM PDT

I am very sorry if I post such a trivial question, but I am really stuck and Google couldn't help me, maybe because I am new with Ruby on Rails.

I have two tables:
Person
id : Integer
name : String

Address
id: Integer
person_id : Integer
name : String

I would like to retrieve a Person joined with an Address. This code snippet works, but only if there is actually an address available for this person:

@person = Person.where('person.id' => params[:id])                   .joins(:address)                   .select('person.id as id, address.id as aid, person.name as name, address.name as aname').first  

My view:

<h2><%= @person.name %></h2>  <p><%= @person.aname %></p>  

Maybe I a m doing something conceptional wrong. As I said as soon as a Person has a related Address, my view displays it, otherwise if there is no Address it prints an error.

Couldn't parse hash in ruby rspec

Posted: 03 May 2016 06:07 AM PDT

i got response from

get 'auth' {:uname => 'apple',:pword => 'xxx'}  puts response.body  

as

"{\"status\":\"Success\",\"success\":\"User is Authenticated and secret token created.\",\"secret_token\":\"1cLojQkX9kuKwhppMPDaEA\"}"  

so how can i parse?

  1. response.body['status'] gives "status"
  2. response.body.status gives undefined method

so how can i get status or token

Rails Deployment to AWS ElasticBeanstalk/RDS failing

Posted: 03 May 2016 06:00 AM PDT

I'm trying out ElasticBeanstalk on AWS for the first time and managed to get my to app environment to display on the AWS console, but deployment fails. My app is connected to a Postgres RDS instance.

The logs tell me that the deployment is failing as a result of the app's hstore requirement. I am installing this extension if it does not exist.

In my application, I have this script setup as a rake task:

# lib/tasks/db_enhancements.rake    ####### Important information ####################  # This file is used to setup a shared extensions #  # within a dedicated schema. This gives us the   #  # advantage of only needing to enable extensions #  # in one place.                                  #  #                                                #  # This task should be run AFTER db:create but    #  # BEFORE db:migrate.                             #  ##################################################      namespace :db do    desc 'Also create shared_extensions Schema'    task :extensions => :environment  do      # Create Schema      ActiveRecord::Base.connection.execute 'CREATE SCHEMA IF NOT EXISTS shared_extensions;'      # Enable triagram      ActiveRecord::Base.connection.execute 'CREATE EXTENSION IF NOT EXISTS pg_trgm SCHEMA shared_extensions;'      # Enable Hstore      ActiveRecord::Base.connection.execute 'CREATE EXTENSION IF NOT EXISTS HSTORE SCHEMA shared_extensions;'    end  end    Rake::Task["db:create"].enhance do    Rake::Task["db:extensions"].invoke  end    Rake::Task["db:test:purge"].enhance do    Rake::Task["db:extensions"].invoke  end  

I also make sure to include the postgres extension in my ebextensions config:

# .ebextensions/packages.config  packages:    yum:      postgresql93-devel: []  

The first error presented in the Deployment log is this:

PG::UndefinedObject: ERROR:  type "hstore" does not exist  

Could anybody help guide me to see what I'm doing incorrectly please?

*PS. I am using the EB CLI

Rails 3.0.2 unescaping get request parameter

Posted: 03 May 2016 05:58 AM PDT

I have 2 applications one with rails 3.0.2 and one with 4.x.x . These applications have an action named redirect_now that takes a request with some parameters and redirects the user where the redirect_to parameters points to.

A request would look something like:

0.0.0.0:3000/redirect_now?param1=lala&param2=lala&redirect_to=http%3A%2F%2Fwww.germanos.ro%2Fapp%2Fsearch.do%3Faction%3DExecute%26searchString%3Dtelevizor%2Bsamsung%26x%3D0%26y%3D0  

This request works fine in the 4.x.x rails app however in the 3.x.x rails app when I type request.url I get:
http://0.0.0.0:3000/redirect_now?param1=lala&param2=lala&redirect_to=http://www.germanos.ro/app/search.do?action=Execute&searchString=televizor+samsung&x=0&y=0" which obviously leads rails into thinking that there are 3 more parameters in the url searchString x, and y instead of using those parameters in the redirect url.

There are no filters or anything that could impact the get request. Any ideas?

Gitlab CI: Is it possible to speed up 'bundle install'?

Posted: 03 May 2016 06:20 AM PDT

I use gitlab.com and CI with the shared docker runner that runs tests for my Ruby on Rails project on every commit to master. I noticed that about 90% of the build time is spent on 'bundle install'. Is it possible to somehow cache the installed gems between commits to speed up the 'bundle install'?

UPDATE:

To be more specific, below is the content of my .gitlab-ci.yml. The first 3 lines of the 'test' script take about 90% of the time making the build run for 4-5 minutes.

image: ruby:2.2.4    services:    - postgres    test:    script:      - apt-get update -qy      - apt-get install -y nodejs      - bundle install --path /cache      - bundle exec rake db:drop db:create db:schema:load RAILS_ENV=test      - bundle exec rspec  

Use inheritance for very similar controllers in rails app

Posted: 03 May 2016 07:02 AM PDT

I have a rails app with two controllers that have very similar behaviors. One is a UsersController related to the concept of Hotel, the other is also named UsersController but related to the concept of association, so it is stored in a folder association :class Api::V1::Association::UsersController < Api::V1::BaseController

These controllers have very similar behaviors, methods with minor differences (they rely on different database tables for certain variables...). I was reading about inheritance and thought that it could be interesting to make the Association::UsersController inherit from the UsersController. Do you think this could be the right thing to do in my case ? For example I have been trying to rewritte the method invite of Association::UsersController to use inheritance but I am a bit confused on how to do it. Could you tell me how you would rewrite this method if the Association::UsersControllerinherits from the usersController. Here how both controllers look like :

users_controller.rb :

class Api::V1::UsersController < Api::V1::BaseController    skip_after_action :verify_authorized, only: [:invite, :update_specific, :show]    before_action :set_user, except: [:invite, :index, :update_specific]    before_action :set_account, only: [:index, :invite, :show]      # creates user linked to account / only account owner can create users linked to account    # input account_id & email    def invite      unless current_user.id != @account.admin_user_id        user_already_exists_or_email_blank?        set_new_user        ActiveRecord::Base.transaction do          set_hotels_access          save_user_and_send_invitation_email        end      else        render_error("not_admin")      end    end      def show      if ((current_user == @user) || (@account.admin == current_user))      else        render_error("unauthorized")      end    end      # admin can update employee or manager    def update_specific      @user_to_update = User.find(params[:id])      if @user_to_update.account != current_user.created_account        render_error("unauthorized")      else        ActiveRecord::Base.transaction do          update_user_and_hotels_access        end      end    end      # update self    def update      authorize @user      if @user.update(user_params)        render_success("updated")      else        render_error("")      end    end      def destroy      authorize @user      if @user.destroy        render json: {message: "User successfully destroyed"}      else        render json: {error: "There was an error please try again"}      end    end    # envoyer account params    def index      if (current_user.created_account == @account) || ((current_user.account == @account) && (current_user.status == "manager"))        @users = policy_scope(User).where(account: @account)        @admin = @account.admin        render json: {users: @users, admin: @admin}      else        render json: {message: "Unauthorized"}      end    end      # unlincks user from account    #input user_id    def unlinck      authorize @user      @user.account = nil      if @user.save && @user.hotels.delete_all.nil?        render json: {user: @user}      else        render_error("db")      end    end      private      def user_already_exists_or_email_blank?      if User.find_by_email(params[:user][:email])        render_error("mail_exists") and return      elsif params[:user][:email].blank?        render_error("empty_email") and return      end    end      def set_new_user      password = SecureRandom.hex      invitation_token = SecureRandom.uuid      @user = User.new(first_name: params[:user][:first_name], last_name: params[:user][:last_name], telephone: params[:user][:telephone], account_id: params[:user][:account_id], email: params[:user][:email], status: params[:user][:status], password: password, password_confirmation: password, invitation_token: invitation_token, invitation_created_at: Time.now, role: "hotel")    end      def set_hotels_access      if params[:hotel_access].first == "all"        @hotels = @account.hotels      else        @hotels = Hotel.where(id: params[:hotel_access])      end    end      def save_user_and_send_invitation_email      if @user.save && @user.hotels << @hotels        if UserMailer.send_invitation(@user, params[:app_base_url]).deliver_now          @user.invitation_sent_at = Time.now          if @user.save            render_success("mail_sent")          else            render_error("db")          end        else          render_error("mail_processing")        end      else        render_error("db")      end    end      def update_user_and_hotels_access      @hotels = Hotel.where(id: params[:hotel_access])      if @user_to_update.hotels.destroy_all        if @user_to_update.hotels << @hotels          if @user_to_update.update(user_params)            render json: {message: "User successfully updated"}          else            render_error("db")          end        else          render("db")        end      else        render_error("db")      end    end      def set_user      @user = User.find(params[:id])    end      def set_account      if params[:account_id]        @account = Account.find(params[:account_id])      elsif params[:user][:account_id]        @account = Account.find(params[:user][:account_id])      end    end      def user_params      params.require(:user).permit(        :email,        :account_id,        :first_name,        :last_name,        :telephone,        :position,        :status,        :user_id      )    end      def render_error(error_type)      case error_type        when "not_admin"           render json: {error: "You are not allowed to create a user for this account"}        when "mail_exists"           render json: {error: "Please fill the email field and try again"}        when "empty_email"          render json: {error: "Please fill the email field and try again"}        when "mail_processing"           render json: { error: "We couldnt send an email to your invitee. Please try again" }        when "db"          render json: {error: "An error occured. Please try again"}        when "unauthorized"          render json: {error: "Unauthorized"}        else          render json: { errors: @user.errors.full_messages }, status: :unprocessable_entity      end    end      def render_success(success_type)      case success_type        when "mail_sent"          render json: { success: "An email was sent to your collaborator asking him to join your Quickbed team." }        when "password_changed"          render json: {success: "Your password was successfully changed"}        when "updated"          render json: {success: "Your infos were successfully updated"}      end    end    end  

association/users_controller.rb

class Api::V1::Association::UsersController < Api::V1::BaseController    skip_after_action :verify_authorized, only: [:invite, :update_specific, :show]    before_action :set_user, except: [:invite, :index, :update_specific]    before_action :set_account_asso, only: [:index, :show, :invite]      # creates user linked to account / only account owner can create users linked to account    # input account_id & email    def invite      unless current_user.id != @account_asso.admin_user_id        user_already_exists_or_email_blank?        set_new_user        ActiveRecord::Base.transaction do          set_offices_access          save_user_and_send_invitation_email        end      else        render_error("not_admin")      end    end      def show      if ((current_user == @user) || (@account_asso.admin == current_user))      else        render_error("unauthorized")      end    end      # admin can update employee or manager    def update_specific      @user_to_update = User.find(params[:id])      if @user_to_update.account != current_user.created_account        render_error("unauthorized")      else        ActiveRecord::Base.transaction do          update_user_and_offices_access        end      end    end      # update self    def update      authorize @user      if @user.update(user_params)        render_success("updated")      else        render_error("db")      end    end      def destroy      authorize @user      if @user.destroy        render json: {message: "User successfully destroyed"}      else        render_error("db")      end    end    # envoyer account params    def index      if (current_user.created_account_asso == @account_asso) || ((current_user.account_asso == @account_asso) && (current_user.status == "manager"))        @users = policy_scope(User).where(account_asso: @account_asso)        @admin = @account_asso.admin        render json: {users: @users, admin: @admin}      else        render_error("unauthorized")      end    end      # unlincks user from account    #input user_id    def unlinck      authorize @user      @user.account_asso = nil      if @user.save && @user.offices.delete_all.nil?        render json: {user: @user}      else        render_error("db")      end    end      private      def user_already_exists_or_email_blank?      if User.find_by_email(params[:user][:email])        render_error("mail_exists") and return      elsif params[:user][:email].blank?        render_error("empty_email") and return      end    end      def set_new_user      password = SecureRandom.hex      invitation_token = SecureRandom.uuid      @user = User.new(first_name: params[:user][:first_name], last_name: params[:user][:last_name], telephone: params[:user][:telephone], account_asso_id: params[:user][:account_asso_id], email: params[:user][:email], status: params[:user][:status], password: password, password_confirmation: password, invitation_token: invitation_token, invitation_created_at: Time.now, role: "asso")    end      def set_offices_access      if params[:office_access].first == "all"        @offices = account_asso.offices      else        @offices = Office.where(id: params[:office_access])      end    end      def save_user_and_send_invitation_email      if @user.save &&  @user.offices << offices        if UserMailer.send_invitation(@user, params[:app_base_url]).deliver_now          @user.invitation_sent_at = Time.now          if @user.save            render_success("mail_sent")          else            render_error("db")          end        else          render_error("mail_processing")        end      else        render_error("db")      end    end      def update_user_and_offices_access     @offices = Office.where(id: params[:office_access])      if @user_to_update.offices.destroy_all        if @user_to_update.offices << @offices          if @user_to_update.update(user_params)            render json: {message: "User successfully updated"}          else            render_error("db")          end        else          render("db")        end      else        render_error("db")      end    end      def set_user      @user = User.find(params[:id])    end      def set_account_asso      if params[:account_asso_id]        @account_asso = AccountAsso.find(params[:account_asso_id])      elsif params[:user][:account_asso_id]        @account_asso = AccountAsso.find(params[:user][:account_asso_id])      end    end      def user_params      params.require(:user).permit(        :email,        :account_id,        :first_name,        :last_name,        :telephone,        :position,        :status,        :user_id      )    end      def render_error(error_type)      case error_type        when "not_admin"           render json: {error: "You are not allowed to create a user for this account"}        when "mail_exists"           render json: {error: "Please fill the email field and try again"}        when "empty_email"          render json: {error: "Please fill the email field and try again"}        when "mail_processing"           render json: { error: "We couldnt send an email to your invitee. Please try again" }        when "db"          render json: {error: "An error occured. Please try again"}        when "unauthorized"          render json: {error: "Unauthorized"}        else          render json: { errors: @user.errors.full_messages }, status: :unprocessable_entity      end    end      def render_success(success_type)      case success_type        when "mail_sent"          render json: { success: "An email was sent to your collaborator asking him to join your Quickbed team." }        when "password_changed"          render json: {success: "Your password was successfully changed"}        when "updated"          render json: {success: "Your infos were successfully updated"}      end    end    end  

Maybe I should rewritte the usersController linked to the concept of Hotel or maybe I should create a third superusersControllerfrom which both the usersController linked to the concept of hotel and the usersController linked to the concept of Association would inherit ? Could you help me find the best fit to my situation ?

Setting credentials for showing static image from Amazon S3

Posted: 03 May 2016 05:58 AM PDT

In my Rails app I want to show static imaged from my AWS S3 bucket. So there is no need to have a solution like Paperclip or Carrierwave, because there is no uploading involved. So I use the aws-sdk gem to interact with the S3 bucket.

This works (of course) fine for public images, but when I want to show private images I get an access denied. I have set the following environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and S3_BUCKET_NAME.

On Heroku I have added these environment variables with heroku config:set and locally I use the dotenv gem.

The problem is that I still have the access denied error, both locally and on Heroku. What is the problem here? This is the view (with a static URL, later this will of course be dynamic):

  = link_to "https://s3-eu-west-1.amazonaws.com/mybucket/Demo/20160503092647717.png" do      = image_tag("https://s3-eu-west-1.amazonaws.com/mybucket/Demo/20160503092647717.png", width: '600')  

Set a page title in rails

Posted: 03 May 2016 05:21 AM PDT

I'm writing a simple imageboard and I want the page titles, i.e. those between <title> tags, change corresponding to the board I'm actually visiting. E.g. I visit the /b/ board, and the page title becomes /b/ - MyChan. I thought to make it something like this:

<% unless current_page?(root_path) %>      <title>          <%= @board.title %> - MyChan      </title>  <% else %>      <title>MyChan</title>  <% end %>  

but I'm not sure if that will work

Rails store and retrieve time only in the following format: hh:mm:ss

Posted: 03 May 2016 05:51 AM PDT

I generated my model like this:

class CreateMyModel < ActiveRecord::Migration    def change      create_table :my_model do |t|        t.references :place, index: true        t.time :time_first        t.time :time_second          t.timestamps      end    end  end  

Saving the model to mysql works fine. The time columns are populated as hh:mm:ss, which is fine. But when I retrieve the entries from mysql, somehow it includes the date from 2000-01-01, example:

2000-01-01T17:00:00Z  

How can I retrieve the time columns as hh:mm:ss?

I'm querying the table entry like this:

my_model = MyModel.find(id)  print my_model.to_json#here time_first and time_second include date.  

devise no longer working on heroku

Posted: 03 May 2016 04:52 AM PDT

I have recently noticed when deploying my app to heroku that the devise gem seems to be causing me some grief due to the ruby version. I have tried lowering the devise version 3.9 but this still didn't fix it

-----> Using set buildpack heroku/ruby  -----> Ruby app detected  -----> Compiling Ruby/Rails  -----> Using Ruby version: ruby-2.0.0  -----> Installing dependencies using bundler 1.11.2         Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment         Fetching gem metadata from https://rubygems.org/...........         Fetching version metadata from https://rubygems.org/...         Fetching dependency metadata from https://rubygems.org/..         Rubygems 2.0.14.1 is not threadsafe, so your gems will be installed one at a time. Upgrade to Rubygems 2.1.0 or higher to enable parallel gem installation.         Using rake 11.1.2         Installing aasm 4.10.0         Using i18n 0.7.0         Using json 1.8.3         Using minitest 5.8.4         Using thread_safe 0.3.5         Using builder 3.2.2         Using erubis 2.7.0         Using mini_portile2 2.0.0         Using rack 1.6.4         Using mime-types-data 3.2016.0221         Using arel 6.0.3         Using execjs 2.6.0         Using bcrypt 3.1.11         Using tilt 2.0.2         Using highline 1.7.8         Using sexp_processor 4.7.0         Using safe_yaml 1.0.4         Using sass 3.4.22         Using temple 0.7.6         Using terminal-table 1.5.2         Using cancancan 1.13.1         Using coffee-script-source 1.10.0         Using thor 0.19.1         Using concurrent-ruby 1.0.1         Using dalli 2.7.6         Using orm_adapter 0.5.0         Installing geocoder 1.3.4         Using jwt 1.5.4         Using kgio 2.10.0         Using memcachier 0.0.2         Using multi_json 1.11.2         Using pg 0.18.4         Installing puma 3.4.0 with native extensions         Using bundler 1.11.2         Using rails_serve_static_assets 0.0.5         Using rails_stdout_logging 0.0.5         Using rolify 5.1.0         Using tzinfo 1.2.2         Installing braintree 2.60.0         Using nokogiri 1.6.7.2         Using rack-test 0.6.3         Using warden 1.2.6         Using mime-types 3.0         Using autoprefixer-rails 6.3.6         Using uglifier 3.0.0         Using haml 4.0.7         Using ruby_parser 3.8.1         Using slim 3.0.6         Using coffee-script 2.4.1         Installing sprockets 3.6.0         Using twilio-ruby 4.11.1         Using rails_12factor 0.0.3         Using activesupport 4.2.4         Using loofah 2.0.3         Using mail 2.6.4         Using material_design_lite-sass 1.1.3         Using ruby2ruby 2.3.0         Using html2haml 2.0.0         Using rails-deprecated_sanitizer 1.0.3         Using globalid 0.3.6         Using activemerchant 1.58.0         Using activemodel 4.2.4         Using rails-html-sanitizer 1.0.3         Using brakeman 3.2.1         Using rails-dom-testing 1.0.7         Using activejob 4.2.4         Using activerecord 4.2.4         Using actionview 4.2.4         Using friendly_id 5.1.0         Using pg_search 1.0.5         Using actionpack 4.2.4         Using actionmailer 4.2.4         Using railties 4.2.4         Using kaminari 0.16.3         Using sprockets-rails 3.0.4         Using coffee-rails 4.1.1         Using responders 2.1.2         Using jquery-rails 4.1.1         Using rails 4.2.4         Using sass-rails 5.0.4         Installing devise 4.0.0         Gem::InstallError: devise requires Ruby version >= 2.1.0.         An error occurred while installing devise (4.0.0), and Bundler cannot continue.         Make sure that `gem install devise -v '4.0.0'` succeeds before bundling.         Bundler Output: Fetching gem metadata from https://rubygems.org/...........         Fetching version metadata from https://rubygems.org/...         Fetching dependency metadata from https://rubygems.org/..         Rubygems 2.0.14.1 is not threadsafe, so your gems will be installed one at a time. Upgrade to Rubygems 2.1.0 or higher to enable parallel gem installation.         Using rake 11.1.2         Installing aasm 4.10.0         Using i18n 0.7.0         Using json 1.8.3         Using minitest 5.8.4         Using thread_safe 0.3.5         Using builder 3.2.2         Using erubis 2.7.0         Using mini_portile2 2.0.0         Using rack 1.6.4         Using mime-types-data 3.2016.0221         Using arel 6.0.3         Using execjs 2.6.0         Using bcrypt 3.1.11         Using tilt 2.0.2         Using highline 1.7.8         Using sexp_processor 4.7.0         Using safe_yaml 1.0.4         Using sass 3.4.22         Using temple 0.7.6         Using terminal-table 1.5.2         Using cancancan 1.13.1         Using coffee-script-source 1.10.0         Using thor 0.19.1         Using concurrent-ruby 1.0.1         Using dalli 2.7.6         Using orm_adapter 0.5.0         Installing geocoder 1.3.4         Using jwt 1.5.4         Using kgio 2.10.0         Using memcachier 0.0.2         Using multi_json 1.11.2         Using pg 0.18.4         Installing puma 3.4.0 with native extensions         Using bundler 1.11.2         Using rails_serve_static_assets 0.0.5         Using rails_stdout_logging 0.0.5         Using rolify 5.1.0         Using tzinfo 1.2.2         Installing braintree 2.60.0         Using nokogiri 1.6.7.2         Using rack-test 0.6.3         Using warden 1.2.6         Using mime-types 3.0         Using autoprefixer-rails 6.3.6         Using uglifier 3.0.0         Using haml 4.0.7         Using ruby_parser 3.8.1         Using slim 3.0.6         Using coffee-script 2.4.1         Installing sprockets 3.6.0         Using twilio-ruby 4.11.1         Using rails_12factor 0.0.3         Using activesupport 4.2.4         Using loofah 2.0.3         Using mail 2.6.4         Using material_design_lite-sass 1.1.3         Using ruby2ruby 2.3.0         Using html2haml 2.0.0         Using rails-deprecated_sanitizer 1.0.3         Using globalid 0.3.6         Using activemerchant 1.58.0         Using activemodel 4.2.4         Using rails-html-sanitizer 1.0.3         Using brakeman 3.2.1         Using rails-dom-testing 1.0.7         Using activejob 4.2.4         Using activerecord 4.2.4         Using actionview 4.2.4         Using friendly_id 5.1.0         Using pg_search 1.0.5         Using actionpack 4.2.4         Using actionmailer 4.2.4         Using railties 4.2.4         Using kaminari 0.16.3         Using sprockets-rails 3.0.4         Using coffee-rails 4.1.1         Using responders 2.1.2         Using jquery-rails 4.1.1         Using rails 4.2.4         Using sass-rails 5.0.4         Installing devise 4.0.0           Gem::InstallError: devise requires Ruby version >= 2.1.0.         An error occurred while installing devise (4.0.0), and Bundler cannot continue.         Make sure that `gem install devise -v '4.0.0'` succeeds before bundling.   !   !     Failed to install gems via Bundler.   !   !     Push rejected, failed to compile Ruby app  

permission Denied whil installing activeadmin

Posted: 03 May 2016 05:31 AM PDT

I am trying to use activeadmin in my Rails app.But when i try to install activeadmin it throws 'permission denied' error. I have added in my Gemfile.

gem 'activeadmin', github: 'activeadmin'  

When I run 'rails generate active_admin:install' I get the following error

**/home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:101:in `initialize': Permission denied @ rb_sysopen - /home/cbls-2/academics/office_management/config/routes.rb (Errno::EACCES)**  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:101:in `open'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:101:in `replace!'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:59:in `invoke!'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:94:in `action'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:30:in `insert_into_file'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/generators/actions.rb:224:in `block in route'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:194:in `block in in_root'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:184:in `block in inside'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/2.3.0/fileutils.rb:128:in `chdir'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/2.3.0/fileutils.rb:128:in `cd'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:184:in `inside'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:194:in `in_root'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/generators/actions.rb:223:in `route'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-4.1.0/lib/generators/devise/devise_generator.rb:22:in `add_devise_routes'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/command.rb:27:in `run'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:126:in `invoke_command'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `block in invoke_all'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `each'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `map'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `invoke_all'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/group.rb:232:in `dispatch'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:115:in `invoke'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/activeadmin-70cfbf3d7d33/lib/generators/active_admin/devise/devise_generator.rb:39:in `create_admin_user'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/command.rb:27:in `run'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:126:in `invoke_command'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `block in invoke_all'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `each'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `map'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `invoke_all'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/group.rb:232:in `dispatch'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:115:in `invoke'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/group.rb:277:in `block in _invoke_for_class_method'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/shell.rb:68:in `with_padding'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/group.rb:266:in `_invoke_for_class_method'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/group.rb:133:in `_invoke_from_option_users'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/command.rb:27:in `run'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:126:in `invoke_command'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `block in invoke_all'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `each'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `map'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `invoke_all'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/group.rb:232:in `dispatch'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/base.rb:440:in `start'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/generators.rb:157:in `invoke'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/generate.rb:13:in `<top (required)>'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:123:in `require_command!'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:130:in `generate_or_destroy'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:50:in `generate'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'  from /home/cbls-2/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'  from bin/rails:9:in `require'  from bin/rails:9:in `<main>'  

ActionCable unable to call on periodic timers

Posted: 03 May 2016 04:33 AM PDT

This is not documented in Rails, but ActionCable has a module called PeriodicTimers https://github.com/rails/rails/blob/master/actioncable/lib/action_cable/channel/periodic_timers.rb

Now in my app/channels/requests_channel.rb I have attempted to test this out by doing:

class RequestsChannel < ApplicationCable::Channel    periodically :transmit_status, every: 2.seconds      def subscribed        stream_from "requests_#{current_user.id}"    end      def unsubscribed    end      private      def transmit_status      puts "ping"    end  end  

and when I connect and subscribe to the stream, nothing shows up in the console. I felt like the code in ActionCable was fairly straight forward, and that this should work but I'm unable to get it to work. Anybody have any experience with this?

Run rq as daemon on server

Posted: 03 May 2016 04:31 AM PDT

In python, I am using rq for the use of background processes. But as I am running same thing on my server also, I want it to run as daemon, apart from unix command does rq provides something to make it daemon, like in ruby we have gem called sidekiq, it provides all the option for running environment, log file or daemon also.

I tried unix command rqworker & but it doesn't seem to be working properly.

Sendgrid API integration using SMTP in rails

Posted: 03 May 2016 04:34 AM PDT

I want to send an email in Ruby. Despite using user credentials I want to use the Sendgrid API for this; I have used the sendgrid-ruby gem.

I want to generate OTP for the authenticated user and give a success response; I am checking OTP via email.

I am getting an following exception:

SendGrid::Exception ({"errors":["The provided authorization grant is     invalid, expired, or revoked"],"message":"error"})  

I have done the following rask in my fp_mailer.rb method:

require 'sendgrid-ruby'      class FPMailer < ActionMailer::Base         def send_otp_email(user, code)                @code = code                @user = user                sendgrid = SendGrid::Client.new do |c|                c.api_key = 'SENDGRID_APIKEY'                end                  email = SendGrid::Mail.new do |m|                m.to = 'abc@.gmail.com'                m.from= 'pqr@gmail.com'                end         sendgrid.send(email)      end    end  

PayPal future payments INTERNAL_SERVICE_ERROR when execute payment

Posted: 03 May 2016 04:02 AM PDT

I'm using Rails 4.2, Ruby 2.2, PayPal-Ruby-SDK , PayPal sandbox

I can create payment, but it has pending status. When I try ti execute it (according to documentation), I get error

INTERNAL_SERVICE_ERROR

REQUEST: Request[post]: https://api.sandbox.paypal.com/v1/payments/payment/PAY-8KG44388FJ2409934K4Q4TYY/execute Request.body={"payer_id":"2"} request.header={"Authorization"=>"Bearer A101.pMlaF6XYq42QPcr-N6cIlwQfyeJNiNwLG6XPMsthrRT3lQ-ENCCIv1X-kFdp2C3_.7s4U_X9jF2hfHtJ-bKPzv-bbmDe", "Content-Type"=>"application/json", "User-Agent"=>"PayPalSDK/PayPal-Ruby-SDK 1.4.4 (paypal-sdk-core 1.4.4; ruby 2.2.4p230-x86_64-linux;OpenSSL 1.0.1f 6 Jan 2014)", "PayPal-Request-Id"=>"9187f64f-bb31-43c3-878c-3b10f5bd9616"}

RESPONSE: Response[400]: Bad Request, Duration: 0.917s Response.body={"name":"INTERNAL_SERVICE_ERROR","message":"An internal service error has occurred","information_link":"https://developer.paypal.com/docs/api/#INTERNAL_SERVICE_ERROR","debug_id":"92f7c262ba80a"} Response.header={"date"=>["Tue, 03 May 2016 10:36:46 GMT"], "server"=>["Apache"], "proxy_server_info"=>["host=slcsbplatformapiserv3002.slc.paypal.com;threadId=410"], "paypal-debug-id"=>["92f7c262ba80a", "92f7c262ba80a"], "correlation-id"=>["92f7c262ba80a"], "content-language"=>["*"], "connection"=>["close", "close"], "set-cookie"=>["X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_version%3D1880%26app%3Dplatformapiserv%26TIME%3D1048520791%26HTTP_X_PP_AZ_LOCATOR%3D; Expires=Tue, 03 May 2016 11:06:46 GMT; domain=.paypal.com; path=/; Secure; HttpOnly", "X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT"], "vary"=>["Authorization"], "content-length"=>["194"], "content-type"=>["application/json"]}

I was trying execute it several days but got same result.

I've written 2 response to PayPal technical support, but I didn't get any answers.

Maybe somebody knows what happened? Thanks!

Rails - Sending a post request by converting get parameters of url_for to post

Posted: 03 May 2016 03:59 AM PDT

I have this url which makes a get request with parameter page.

<%= link_to 'Next', url_for(:page => @results.next_page_params) %>  

Now I want to make a post request instead because my URL for get request is too long for webrick to handle.

So I did something like this:

<%=form_tag() do%>    <%= hidden_field_tag(:page, @results.next_page_params) %>    <%= submit_tag("Next page") %>  <%end%>  

Problem So the above code does make post request but not in the same format as url_for method. I want to make post request in the same exact format.

How can I make the post request in the same format as url_for ?

1 comment:

  1. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
    ruby on rails training India
    ruby on rails training Hyderabad

    ReplyDelete