Tuesday, May 31, 2016

Why is valid_date? for now is true, but for tomorrow is false? | Fixed issues

Why is valid_date? for now is true, but for tomorrow is false? | Fixed issues


Why is valid_date? for now is true, but for tomorrow is false?

Posted: 31 May 2016 07:01 AM PDT

Doing some validation for dates I found that valid_date? is giving me a false value if the date is in the future (date after current date) but all other dates is true.

Example:

These return true:

valid_date? DateTime.strptime(DateTime.yesterday.strftime("%m-%d-%Y"), "%m-%d-%Y")

valid_date? DateTime.strptime(DateTime.now.strftime("%m-%d-%Y"), "%m-%d-%Y")

But this returns false

valid_date? DateTime.strptime(DateTime.tomorrow.strftime("%m-%d-%Y"), "%m-%d-%Y")

Can anyone explain the reason for this?

Having trouble with HTTParty (SocketError)

Posted: 31 May 2016 07:01 AM PDT

I'm learning how to work with HTTParty and API. I'm trying to make a simple query from my RoR app, but every time I have the same error: getaddrinfo: No such host is known.(SocketError)

My courses_controller.rb looks like

class CoursesController < ApplicationController    def index      @search_term = "jhu"      @courses = Coursera.for(@search_term)    end  end  

and the model coursera.rb is

class Coursera    include HTTParty      base_uri 'https:/api.coursera.org/api/catalog.v1/courses'    default_params fields: "smallIcon, shortDescription", q: "search"    format :json      def self.for term      get("", query: { query: term})["elements"]    end  end  

I was trying to use another base_uri but it doesn't works.

ActiveRecord query in views and helpers in Rails

Posted: 31 May 2016 06:59 AM PDT

I have the following associations defined in my application:

class Person    belongs_to :type  end    class Type    has_many :people  end  

Now, in the new and edit form for person, I need to give a dropdown that will show all the types which will come from the Type model.

Now there are two approach to do the same:

1. make an instance variable in controller for types and access that in the form view.

class PeopleController       before_action :get_types, only: [:new, :create, :edit, :update]      def new      end      def create    end      def edit    end      def update    end      private      def get_types      @types = Type.all    end    end  

person/_form.html.erb

...  <%= f.select :type_id, @types.collect{ |type| [type.name, type.id]} %>  ...  

2. Making a database query in the person_helper

person_helper.rb

module PersonHelper    def get_types      Type.all    end  end  

person/_form.html.erb

...  <%= f.select :type_id, get_types.collect{ |type| [type.name, type.id]} %>  ...  


So, I want to know which is the better approach and why.

Note: As per MVC paradigm, controller will provide the necessary data to the views. Neither I am not able to find any difference in the query execution in both the cases nor, I am able to find any good explanation regarding the same apart from the MVC part.

Gettitng "uninitialized constant" when tryhing to invoke my service in Rails

Posted: 31 May 2016 06:57 AM PDT

I"m using Rails 4.2.3. I have this line in a controller

    service = XACTEService.new("Event", '2015-06-01', 'Zoo')  

The class in question is defined in app/services/XACTEService.rb. However upon visiting my controller, I get the error

uninitialized constant MyObjectsController::XACTEService  

However, I have added this into my config/application.rb file

  class Application < Rails::Application      config.autoload_paths += %W(#{config.root}/services)  

So I don't understand why the controller is failing to find my service.

angular not rendering templates

Posted: 31 May 2016 07:01 AM PDT

i have a rails app that i have started to link in with angular, when using the following code in my js everything working until i put in the routes/templates

merchant = angular.module('CupTown', [ 'ngResource' ])  #Factory  merchant.factory 'Merchants', [    '$resource'    ($resource) ->      $resource '/shopping/merchants.json', {},        query:          method: 'GET'          isArray: true        create: method: 'POST'  ]  merchant.factory 'Merchant', [    '$resource'    ($resource) ->      $resource '/shopping/merchants/:id.json', {},        show: method: 'GET'        update:          method: 'PUT'          params: id: '@id'        delete:          method: 'DELETE'          params: id: '@id'  ]  #Controller  merchant.controller 'MerchantCtrl', [    '$scope'    '$http'    '$resource'    'Merchants'    'Merchant'    '$location'    ($scope, $http, $resource, Merchants, Merchant, $location) ->      $scope.merchants = Merchants.query()        $scope.deleteMerchant = (merchantId) ->        if confirm('Are you sure you want to delete this merchant?')          Merchant.delete { id: merchantId }, ->            $scope.merchants = Merchants.query()            $location.path '/merchants'            return        return        return  ]      #Routes  merchant.config [    '$routeProvider'    '$locationProvider'    ($routeProvider, $locationProvider) ->      $routeProvider.when '/merchants',        templateUrl: '/templates/merchants/index.html'        controller: 'MerchantCtrl'      $routeProvider.otherwise redirectTo: '/merchants'      return  ]  

my templates are in /public/merchants/

<div class='mdl-cell mdl-cell--12-col' ng-controller='MerchantCtrl'>      <h3 ng-hide='merchants.length'>          No merchants      </h3>      <ul class='merchant-list-three mdl-list' ng-repeat='merchant in merchants' ng-show='merchants.length'>          <a href='#/merchant/{{merchant.permalink}}'>              <li class='mdl-list__item mdl-list__item--three-line'>          <span class='mdl-list__item-primary-content'>            <span>{{merchant.name}}</span>          </span>          <span class='mdl-list__item-secondary-content'>            <i class='material-icons'>              chevron_right            </i>          </span>              </li>          </a>      </ul>  </div>  

application.html.ham

!!!  %html{lang: :en, 'ng-app' => 'CupTown'}    %head      = render 'shared/meta_data'      = stylesheet_link_tag 'application'      = yield :head      / Material Design icon font      %link{:href => '//fonts.googleapis.com/icon?family=Material+Icons', :rel => 'stylesheet'}/      = csrf_meta_tags    %body{'ng-view' => ''}      / Always shows a header, even in smaller screens.      .mdl-layout.mdl-js-layout.mdl-layout--fixed-header        %header.mdl-layout__header          .mdl-layout__header-row            / Title            .mdl-layout-title= content_for?(:title) ? yield(:title).upcase : t('.site_name')            .mdl-layout-spacer            / Navigation. We hide it in small screens.            %nav.mdl-navigation.mdl-layout--large-screen-only            %nav.mdl-navigation              - if signed_in?                = render 'shared/top_cart'        - if signed_in?          .mdl-layout__drawer            / Display brand logo within drawer header            %span.mdl-layout-title            = render 'shared/compact_menu'        %main.mdl-layout__content          .page-content            .mdl-grid              - flash.each do |key, value|                %div{:class => "alert alert-#{key}"}= value              = yield        = render 'shared/footer'      %script{:defer => '', :src => '//code.getmdl.io/1.1.3/material.min.js'}      %script{:defer => '', :src => '//js.braintreegateway.com/v2/braintree.js'}      = javascript_include_tag 'application'  

How does sidekiq know when a batch has all its jobs?

Posted: 31 May 2016 06:04 AM PDT

batch = Sidekiq::Batch.new  batch.description = "Batch description (this is optional)"  batch.on(:success, MyCallback, :to => user.email)  batch.jobs do    rows.each { |row| RowWorker.perform_async(row) }  end    sleep(x_seconds)    batch.jobs do    rows.each { |row| RowWorker.perform_async(row) }  end    puts "Just started Batch #{batch.bid}"  

In the above code it could be possible that the callback is called before the next batch jobs are added..so is there a way to inform sidekiq pro to not call the callback as the jobs in the batch are yet to be added?

How to send JSON response from Rails to Native Application?

Posted: 31 May 2016 06:38 AM PDT

I have two application 1 from native application (Mobile) and another is website. In mobile application, I have searching functionality.

In mobile, I have one page in that I can post my products. I can select my products through barcode scan or through web-url.

There will be two button for selecting my products barcode scan and search through web-url.

When I click on Search button, It will open web-url in webView in mobile. Now, I will select my products and submit the form (In RAILS).

Now, How can I pass json response to native application that my selected products will display on my post page?

Rails: How to apply background-color to body

Posted: 31 May 2016 07:01 AM PDT

Although I'd like to apply background color to body in my rails app, it doesn't work.

application.css

body {    background-color: red;  }  

application.html.erb

<!DOCTYPE html>  <html>  <head>    ...  </head>  <body>    <%= render 'layouts/header' %>    ...  

It would be appreciated if you could give me any suggestion though this is an obvious question

How to use devise parent_controller for devise inherited controller but skip for ActiveAdmin devise controller?

Posted: 31 May 2016 06:39 AM PDT

I am developing Api based application, site.com (Client App), api.site.com (Server App)

In my api.site.com, there are passwords, confirmations controller, which are inherited from the Devise controllers. By default Devise parent controller is Application controller, but Devise inherited controllers need to pass through ApiBaseController api_authentication action. So, Devise.rb has following configuration:

config.parent_controller = 'ApiBaseController'  

Api authentication is working fine now.

ApiBaseController sample code:

class ApiBaseController < ApplicationController    before_action :api_authentication      def api_authentication      api_key = request.headers['Api-Key']      @app = Application.find_by_api_key(api_key) if api_key      unless @app       return render json: { errors: { message: 'Something went wrong, contact admin', code: '1000' } }      end    end  end  

Now i am using ActiveAdmin, after installing ActiveAdmin i tried to open http://localhost:3000/admin/login on browser, I saw following error response on browser instead of active admin login page:

{"errors":{"message":"Something went wrong, contact admin","code":1000}}

I checked the issue, and i realized that active_admin/devise/sessions controller also passed through ApiBaseController. This is because we had set our parent controller to ApiBaseController (config.parent_controller = 'ApiBaseController'). I removed the code and ActiveAdmin worked fine.

But passwords, confirmations controller did not passed through the ApiBaseController api_authentication() since i removed the Devise configuration (config.parent_controller = 'ApiBaseController').

So if you guys have understood the problem, please let me know the solution.

In summary, i need all the api Devise inherited controllers need to pass through ApiBaseController for api_authentication() check and ActiveAdmin Devise controllers do not need to pass through ApiBaseController.

Thanks in advance.

Change color of the label in a Simple Form

Posted: 31 May 2016 05:40 AM PDT

How can I change the color of a field's label in Simple Form? Now it's black but I want it to be white.. I'm using scss. I tried this code below but it's not working:

label {      float: left;      width: 100px;      text-align: right;      margin: 2px 10px;      color: #ffffff;      }  

and html output of the field

<div class="form-group email optional user_email"><label class="email optional control-label" for="user_email">Email</label><input class="string email optional form-control" placeholder="user@domain.com" type="email" value="test@gmail.com" name="user[email]" id="user_email"></div>  

How to access a video thumbnail saved using paperclip and paperclip-av-transcoder

Posted: 31 May 2016 05:20 AM PDT

I am using paperclip and paperclip-av-transcoder to save a video and create thumbnail for it while saving. Paperclip model as follows.

class NewsAssets::Video < NewsAssets::Base      has_attached_file :attachment,:styles => {      :thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10 },:medium => {:geometry => "640x480", :format => 'mp4' }      }, :processors => [:transcoder],      :path => (Rails.env.development? ? "#{Rails.root}/public/sys_path/:styles/:basename.:extension" : "public/sys_path/:styles/:basename.:extension"),      :url => (Rails.env.development? ? "/sys_path/:styles/:basename.:extension" : ':s3_alias_url'),      :storage => (Rails.env.development? ? :filesystem : :s3),      :s3_permissions => 'public_read'  end  

after saving the video thumbnail is creating inside a folder as a jpg image.

public/sys_path/thumbs/file.jpg  

But not able to retrieve it. I am using rails-4. Is there any papercrip way or method to retrieve the thumb?

How to encode emoji while sending to server (Ruby on Rails)?

Posted: 31 May 2016 05:00 AM PDT

While I am sending the emoji to server "\ud83d\ude0e" (emoji unicode) in the given format, the server could not understand the code and while sending push notification from server to device, the notification is not coming.

I have used :

NSData *data = [self.activeTextField.text dataUsingEncoding:NSNonLossyASCIIStringEncoding];  NSString *goodValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  

to encode the message(emoji) while sending and used:

NSData *data = [[arrChat objectAtIndex:3] dataUsingEncoding:NSUTF8StringEncoding];  NSString *goodValue = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding];  

while receiving the messages.

Please suggest how to resolve this issue

Thanks

How tune correct stream music if users listen the same music track?

Posted: 31 May 2016 04:29 AM PDT

I develop playlist with music, whe user can listen music. I founded post with example solution - music stream

Can you point me to a way to stream music so that when anyone lands on the page and clicks play they listen the same music track? What may face difficulties? Maybe there are ready solutions? Wich gem need to use? Thanks for advance for your answer.

How van I allow index only for same profile?

Posted: 31 May 2016 07:01 AM PDT

My app is a weight loss app. It uses Devise for user authentication.

A user has_one :profile (the profile table holds the user_id as foreign key) that stores data like prename, surname etc. and is created automatically when a user signs up. A profile has_many :weights (users of the app should weigh themselves regularly and store their new weight in this table). So far so good.

I have the following problem: If a logged in user goes to the index page of the weight controller he sees only his own weights. However, if this user now changes the profile_id in the URL bar he can also see the weights of that other profile (although it is not "his" profile). Additionally, he can now create a new weight, which then holds the other profile_id (which is obviously not his own).

What I managed to do is to generally restrict users to edit or destroy weights which do not hold their own profile_id (through before_action :require_same_weight_profile in my weights_controller.rb).

My question now: how can I prevent this user (that has a certain profile) to do the stuff described above?

I'm sure the answer is pretty simple (I started coding just a few months ago).

UPDATE In the meanwhile I found a solution. Unfortunately the suggested solutions in the comments did not work for me. What does work is the following:

My update in weights_controller.rb

before_filter :require_permission    ...    def require_permission    if current_user != Profile.find(params[:profile_id]).user      redirect_to root_path    end  end  

routes.rb

Rails.application.routes.draw do      devise_for :users    resources :profiles, only: [:index, :show, :edit, :update] do      resources :weights      end  

profile.rb

class Profile < ActiveRecord::Base    belongs_to :user    belongs_to :pal    has_many :weights, dependent: :destroy    belongs_to :goal  end  

weight.rb

class Weight < ActiveRecord::Base    belongs_to :profile  end  

weights_controller.rb

class WeightsController < ApplicationController    before_action :set_profile    before_action :load_profile    before_action :set_weight, only: [:show, :edit, :update, :destroy]    before_action :require_same_weight_profile, only: [:show, :edit, :update, :destroy]        # GET /weights    # GET /weights.json    def index      @weights = Profile.find(params[:profile_id]).weights    end      # GET /weights/1    # GET /weights/1.json    def show    end      # GET /weights/new    def new      @weight = Weight.new(:profile_id => params[:profile_id])    end      # GET /weights/1/edit    def edit    end      # POST /weights    # POST /weights.json    def create      @weight = Weight.new(weight_params)        respond_to do |format|        if @weight.save          format.html { redirect_to profile_weights_path, notice: 'Weight was successfully created.' }          format.json { render :show, status: :created, location: @weight }        else          format.html { render :new }          format.json { render json: @weight.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /weights/1    # PATCH/PUT /weights/1.json    def update      respond_to do |format|        if @weight.update(weight_params)          format.html { redirect_to profile_weights_path, notice: 'Weight was successfully updated.' }          format.json { render :show, status: :ok, location: @weight }        else          format.html { render :edit }          format.json { render json: @weight.errors, status: :unprocessable_entity }        end      end    end      # DELETE /weights/1    # DELETE /weights/1.json    def destroy      @weight.destroy      respond_to do |format|        format.html { redirect_to profile_weights_path, notice: 'Weight was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_weight        @weight = Weight.find(params[:id])      end        def set_profile        @profile = Profile.find_by(user_id: params[:id])      end        def load_profile        @profile = current_user.profile #|| current_user.build_profile      end        # Never trust parameters from the scary internet, only allow the white list through.      def weight_params        params.require(:weight).permit(:profile_id, :weight, :weight_day)      end        # This checks if the current user wants to deal with weights other than his own      def require_same_weight_profile        if @weight.profile_id != current_user.profile.id          flash[:danger] = "You can only edit or delete your own weights"          redirect_to profile_weights_path(current_user.profile)        end      end  end  

profiles_controller.rb

class ProfilesController < ApplicationController    before_action :set_profile, only: [:show, :edit, :update, :destroy]    before_action :load_profile        # GET /profiles    # GET /profiles.json    def index      @profiles = Profile.all    end      # GET /profiles/1    # GET /profiles/1.json    def show    end      # GET /profiles/new    def new      @profile = Profile.new    end      # GET /profiles/1/edit    def edit    end      # POST /profiles    # POST /profiles.json    def create      @profile = Profile.new(profile_params)      @profile.user = current_user        respond_to do |format|        if @profile.save          format.html { redirect_to @profile, notice: 'Profile was successfully created.' }          format.json { render :show, status: :created, location: @profile }        else          format.html { render :new }          format.json { render json: @profile.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /profiles/1    # PATCH/PUT /profiles/1.json    def update      respond_to do |format|        if @profile.update(profile_params)          format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }          format.json { render :show, status: :ok, location: @profile }        else          format.html { render :edit }          format.json { render json: @profile.errors, status: :unprocessable_entity }        end      end    end      # DELETE /profiles/1    # DELETE /profiles/1.json    def destroy      @profile.destroy      respond_to do |format|        format.html { redirect_to profiles_url, notice: 'Profile was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_profile        @profile = Profile.find_by(user_id: params[:id])      end        def load_profile        @profile = current_user.profile #|| current_user.build_profile      end        # Never trust parameters from the scary internet, only allow the white list through.      def profile_params        params.fetch(:profile, {}).permit(:prename, :surname, :birthdate, :gender, :size, :pal_id)       end    end  

Capistrano Rails deploy Passenger error

Posted: 31 May 2016 04:41 AM PDT

I deployed my Rails application to my local IP address. After the successful deployment, when I opened the page in browser, I get the following error. I have been stuck with the following issue for sometime.

It looks like Bundler could not find a gem. Maybe you didn't install all the gems that this application needs. To install your gems, please run:        bundle install    If that didn't work, then the problem is probably caused by your application being run under a different environment than it's supposed to. Please check the following:    Is this app supposed to be run as the deploy user?  Is this app being run on the correct Ruby interpreter? Below you will see which Ruby interpreter Phusion Passenger attempted to use.  -------- The exception is as follows: -------    Could not find rake-10.4.2 in any of the sources (Bundler::GemNotFound)    /home/deploy/.gem/ruby/2.2.2/gems/bundler-1.12.5/lib/bundler/spec_set.rb:95:in `block in materialize'    /home/deploy/.gem/ruby/2.2.2/gems/bundler-1.12.5/lib/bundler/spec_set.rb:88:in `map!'    ...  

I verified this stackoverflow link and tried the following things.

I did bundle install multiple times as deploy user.

I had 2 versions of rake installed, 11.1.2 and 10.4.2. I purged 11.1.2. Made sure this version is not there anywhere.

I see 2 ruby versions. 1.9.3 and 2.2.2. Not sure if this is the issue. I did not manually install 1.9.3. But I see the folders /usr/local/src/ruby-1.9.3-p448 and /opt/rubies/ruby-1.9.3-p448. When I tried to remove 1.9.3, using sudo apt-get remove ruby 1.9.3 I got the following result. In the end, I did not remove it as it was trying to remove passenger itself.

Reading package lists... Done  Building dependency tree  Reading state information... Done  Note, selecting 'libghc-hxt-xslt-dev-9.1.1-9b3da' for regex '1.9.3'  Note, selecting 'ruby1.9.3' for regex '1.9.3'  Note, selecting 'libghc-hxt-xslt-prof-9.1.1-9b3da' for regex '1.9.3'  Note, selecting 'libghc-hxt-xslt-dev' instead of 'libghc-hxt-xslt-dev-9.1.1-9b3da'  Note, selecting 'libghc-hxt-xslt-prof' instead of 'libghc-hxt-xslt-prof-9.1.1-9b3da'  Package 'ruby1.9.3' is not installed, so not removed  The following packages will be REMOVED    libruby2.1 passenger passenger-dev ri ruby ruby-dev ruby-full ruby-rack ruby2.1 ruby2.1-dev  

Any help related to this issue is appreciated.

EDIT: I see files related to rake 11.1.2 still

/home/deploy/myapp/vendor/cache/rake-11.1.2.gem  /home/deploy/myapp/vendor/cache/ruby/2.2.0/specifications/rake-11.1.2.gemspec  /home/deploy/myapp/vendor/cache/ruby/2.2.0/cache/rake-11.1.2.gem  /home/deploy/myapp/vendor/cache/ruby/2.2.0/gems/rake-11.1.2  /home/deploy/myapp/vendor/cache/ruby/2.1.0/specifications/rake-11.1.2.gemspec  /home/deploy/myapp/vendor/cache/ruby/2.1.0/cache/rake-11.1.2.gem  /home/deploy/myapp/vendor/cache/ruby/2.1.0/gems/rake-11.1.2  /home/deploy/.gem/ruby/2.2.2/doc/rake-11.1.2  /home/deploy/.gem/specs/api.rubygems.org%443/quick/Marshal.4.8/rake-11.1.2.gemspec  /var/lib/gems/2.1.0/doc/rake-11.1.2  

Could this be the problem?

I share the Ruby Environment details below.

RubyGems Environment:     RUBYGEMS VERSION: 2.4.5     RUBY VERSION: 2.2.2 (2015-04-13 patchlevel 95) [x86_64-linux]     INSTALLATION DIRECTORY: /home/deploy/.gem/ruby/2.2.2     RUBY EXECUTABLE: /opt/rubies/ruby-2.2.2/bin/ruby     EXECUTABLE DIRECTORY: /home/deploy/.gem/ruby/2.2.2/bin     SPEC CACHE DIRECTORY: /home/deploy/.gem/specs     SYSTEM CONFIGURATION DIRECTORY: /opt/rubies/ruby-2.2.2/etc     RUBYGEMS PLATFORMS:       ruby       x86_64-linux     GEM PATHS:       /home/deploy/.gem/ruby/2.2.2       /opt/rubies/ruby-2.2.2/lib/ruby/gems/2.2.0     GEM CONFIGURATION:       :update_sources => true       :verbose => true       :backtrace => false       :bulk_threshold => 1000     REMOTE SOURCES:       https://rubygems.org/     SHELL PATH:       /home/deploy/.gem/ruby/2.2.2/bin       /opt/rubies/ruby-2.2.2/lib/ruby/gems/2.2.0/bin       /opt/rubies/ruby-2.2.2/bin       /usr/local/sbin       /usr/local/bin       /usr/sbin       /usr/bin       /sbin       /bin       /usr/games       /usr/local/games  

Nginx conf file /etc/nginx/nginx.conf is as follows.

user www-data;  worker_processes 4;  pid /run/nginx.pid;    events {      worker_connections 768;      # multi_accept on;  }    http {        ##      # Basic Settings      ##        sendfile on;      tcp_nopush on;      tcp_nodelay on;      keepalive_timeout 65;      types_hash_max_size 2048;      # server_tokens off;        # server_names_hash_bucket_size 64;      # server_name_in_redirect off;        include /etc/nginx/mime.types;      default_type application/octet-stream;        ##      # SSL Settings      ##        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE      ssl_prefer_server_ciphers on;        ##      # Logging Settings      ##        access_log /var/log/nginx/access.log;      error_log /var/log/nginx/error.log;        ##      # Gzip Settings      ##        gzip on;      gzip_disable "msie6";        # gzip_vary on;      # gzip_proxied any;      # gzip_comp_level 6;      # gzip_buffers 16 8k;      # gzip_http_version 1.1;      # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;        ##      # Phusion Passenger config      ##      # Uncomment it if you installed passenger or passenger-enterprise      ##        passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;      passenger_ruby /usr/bin/ruby;        ##      # Virtual Host Configs      ##        include /etc/nginx/conf.d/*.conf;      include /etc/nginx/sites-enabled/*;  }  

Nginx sites-enabled default file

server {      listen 80 default_server;      listen [::]:80 default_server ipv6only=on;        server_name 192.xxx.xxx.xxx;      passenger_enabled on;      rails_env    prelive;      root         /home/deploy/myapp/current/public;        # redirect server error pages to the static page /50x.html      error_page   500 502 503 504  /50x.html;      location = /50x.html {          root   html;      }  }  

How to dynamically add text fields on Rails 4? (not nested)

Posted: 31 May 2016 04:19 AM PDT

I'm very new to Rails and I need to dynamically add/remove input fields on a "form_for" in Rails. I am using these inputs to alter a user's profile.

Here's the snippet I want to turn dynamic:

<%= f.label :languages, "Languages" %>  <%= f.text_field :languages, class: "shortInput", value: @parsed_json_user['user']['languages']%> <br />  

I have seen many tutorials using nested attributes (I'm not even exactly sure about what those are) and such but I will not be using models. As you can see, I just want an object with a multitude of values (e.g. array) since I'll be using an API to update the "User" model.

I need something like:

Languages:
English remove
add new

Should I be using fields_for? Or somehow use JS or JQuery? Any help would be appreciated.

I searched everywhere for a similar question and haven't found any but if you actually know of or find one, pointing me in the right direction would be wonderful!

Thanks in advance

Ruby on Rails - Increment by 1 from last object

Posted: 31 May 2016 04:10 AM PDT

I am building a user gallery application, where user can create albums and upload images to their album. I am using nested forms for images.

In my images database, I have a column called sort_order. I want to use sort_order to manage the sorting and showing user, for ex: he is seeing 3 of 12 images, where 3 is number of sort_order and 12 is number of total images in that album.

sort_order is integer and default: 0. What I looking for is to increase/increment number of sort_order for each image based on previous sort_order of last image in same album.

For ex: image 1 will have sort_order: 1, image 2 will then have previous images sort_id +1 => sort_order: 2 and so on.

How can I make it so after saving the images, I increment by 1 from last objects sort_order.

I have been testing with code below, but it just add 1 for all objects:

after_create :updating_sort_order    def updating_sort_order    self.sort_order += 1  end  

If there is another way to do it without having the sort_order column, I am open to it.

Rails app using existing database MySQL

Posted: 31 May 2016 07:00 AM PDT

I'm a RoR developer and I'm used to create my own databases using scaffold and such. However I was told to create a rails app to an existing populated database. I Searched and i found this:

1. write config/database.yml to reference your database.  2. Run "rake db:schema:dump" to generate db/schema.rb.  Here's the  documentation:     $ rake -T db:schema:dump  ...  rake db:schema:dump # Create a db/schema.rb file that can be  portably used against any DB supported by AR    3. Convert schema.rb into db/migrate/001_create_database.rb:    Class CreateMigration < ActiveRecord::Migration  def self.up  # insert schema.rb here  end    def self.down  # drop all the tables if you really need  # to support migration back to version 0  end  end  

However I saw some comments saying that they lost their data and some saying that it worked. I can't take chances to lose the data from the database. Can someone please give me some more solid explanation? Or a better solution

Conversion from Elasticsearch::Model::Response::Records to Kaminari::PaginatableArray

Posted: 31 May 2016 04:04 AM PDT

This is what I have:

@parts = if params[:q].present?             Part.search(params[:q]).records           else             Part.find_by_params(params)           end  

Pagination doesn't work (with Elasticsearch::Model::Response::Records) if condition is true.

Is there any way I can convert Elasticsearch::Model::Response::Records to Kaminari::PaginatableArray?

carrierwaver doesn't save image in postgresql

Posted: 31 May 2016 03:36 AM PDT

Hi guys I'm using carrierwave on my rails app to upload images from the computer to create new items.. If I create the item without uploading an image, the item will be saved into the database, otherwise it won't. So there's must be something wrong with my settings for the carrierwave. can anyone give me an hand, identifing the mistake(s)?

FORM HTML

 <form action="/items" method="post" enctype='multipart/form-data'>      <%= hidden_field_tag :authenticity_token, form_authenticity_token %>    <label>Name</label>    <input type="text" name="name">      <label>Size</label>    <input type="text" name="size">      <label>Image</label>    <input type="file" name="image">      <label>Description</label>    <textarea name="description"></textarea>      <label>Price</label>    <input type="number" name="price" placeholder="price $$">       <button> Save </button>    </form>  

IMAGE UPLOADER

  class ImageUploader < CarrierWave::Uploader::Base       include CarrierWave::MiniMagick       storage :file       def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"     end       version :thumb do      process :resize_to_fit => [150, 150]     end         def extension_white_list      %w(jpg jpeg gif png)     end   end  

GEM INSTALLED

   gem 'carrierwave'       gem "mini_magick"  

ITEM MODEL

 class Item < ActiveRecord::Base      mount_uploader :image, ImageUploader        belongs_to :category     end  

ITEM CONTROLLER

 class ItemsController < ApplicationController         def index         @items = Item.all       end         def create        item = Item.new        item.name = params[:name]        item.image = params[:image]        item.size = params[:size]        item.description = params[:description]        item.price = params[:price]        if item.save          render :show        else          puts "error"        end      end     def show    @item = Item.find(params[:id])   end     def update     @item = Item.find(params[:id])     @item.name = params[:name]     @item.image = params[:image]     @item.size = params[:size]     @item.description = params[:description]     @item.price = params[:price]   end     def destroy     @item = Item.find(params[:id])     @item.destroy    end  end  

ROR can't connect remotely to MySQL DB [duplicate]

Posted: 31 May 2016 03:00 AM PDT

This question already has an answer here:

I want to establish_connection to database on other machine:

require 'mysql2'  require "active_record"  

Using ActiveRecord

ActiveRecord::Base.establish_connection(  :adapter=> 'mysql2',  :database=> 'development_db',  :host=> "192.168.1.135",  :port=> "3306",  :username=> 'username',  :password=>'password'  )  

get following error : Can't connect to MySQL server on '192.168.1.135' (111) (Mysql2::Error)

Exiting while starting the server: rails s

Posted: 31 May 2016 03:53 AM PDT

Exiting while starting the server: rails s. My OS is Ubuntu 12.04.The terminal output listed below.

rails s  => Booting Thin  => Rails 4.2.6 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  => Ctrl-C to shutdown server  

Exiting

 /home/jobi/Music/inaturalist-master/config/environments/development.rb:23:in `initialize': No such file or directory - /home/jobi/Music/inaturalist-master/config/smtp.yml (Errno::ENOENT)    from /home/jobi/Music/inaturalist-master/config/environments/development.rb:23:in `open'    from /home/jobi/Music/inaturalist-master/config/environments/development.rb:23:in `block in <top (required)>'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/railtie.rb:210:in `instance_eval'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/railtie.rb:210:in `configure'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/railtie.rb:182:in `configure'    from /home/jobi/Music/inaturalist-master/config/environments/development.rb:1:in `<top (required)>'    from /usr/local/lib/ruby/gems/2.0.0/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'    from /usr/local/lib/ruby/gems/2.0.0/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'    from /usr/local/lib/ruby/gems/2.0.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require'    from /usr/local/lib/ruby/gems/2.0.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'    from /usr/local/lib/ruby/gems/2.0.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/engine.rb:598:in `block (2 levels) in <class:Engine>'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/engine.rb:597:in `each'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/engine.rb:597:in `block in <class:Engine>'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `instance_exec'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `run'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/initializable.rb:55:in `block in run_initializers'    from /usr/local/lib/ruby/2.0.0/tsort.rb:150:in `block in tsort_each'    from /usr/local/lib/ruby/2.0.0/tsort.rb:183:in `block (2 levels) in each_strongly_connected_component'    from /usr/local/lib/ruby/2.0.0/tsort.rb:210:in `block (2 levels) in each_strongly_connected_component_from'    from /usr/local/lib/ruby/2.0.0/tsort.rb:219:in `each_strongly_connected_component_from'    from /usr/local/lib/ruby/2.0.0/tsort.rb:209:in `block in each_strongly_connected_component_from'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/initializable.rb:44:in `each'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/initializable.rb:44:in `tsort_each_child'    from /usr/local/lib/ruby/2.0.0/tsort.rb:203:in `each_strongly_connected_component_from'    from /usr/local/lib/ruby/2.0.0/tsort.rb:182:in `block in each_strongly_connected_component'    from /usr/local/lib/ruby/2.0.0/tsort.rb:180:in `each'    from /usr/local/lib/ruby/2.0.0/tsort.rb:180:in `each_strongly_connected_component'    from /usr/local/lib/ruby/2.0.0/tsort.rb:148:in `tsort_each'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/initializable.rb:54:in `run_initializers'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/application.rb:352:in `initialize!'    from /home/jobi/Music/inaturalist-master/config/environment.rb:5:in `<top (required)>'    from /usr/local/lib/ruby/gems/2.0.0/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'    from /usr/local/lib/ruby/gems/2.0.0/gems/polyglot-0.3.5/lib/polyglot.rb:65:in `require'    from /usr/local/lib/ruby/gems/2.0.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require'    from /usr/local/lib/ruby/gems/2.0.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'    from /usr/local/lib/ruby/gems/2.0.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'    from /home/jobi/Music/inaturalist-master/config.ru:3:in `block in <main>'    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `instance_eval'    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `initialize'    from /home/jobi/Music/inaturalist-master/config.ru:in `new'    from /home/jobi/Music/inaturalist-master/config.ru:in `<main>'    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `eval'    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `new_from_string'    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:40:in `parse_file'    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.6.4/lib/rack/server.rb:299:in `build_app_and_options_from_config'    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.6.4/lib/rack/server.rb:208:in `app'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/commands/server.rb:61:in `app'    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.6.4/lib/rack/server.rb:336:in `wrapped_app'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/commands/server.rb:139:in `log_to_stdout'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/commands/server.rb:78:in `start'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:80:in `block in server'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `tap'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `server'    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'    from /usr/local/lib/ruby/gems/2.0.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>'  

Multiple image uploads in Rails from the same form_for?

Posted: 31 May 2016 03:17 AM PDT

I am having some trouble figuring out how to upload multiple images using a single form in a view. Basically, I have a form for articles on a blog that consists of a title text_field, a body text_area and a file_field for uploading a single picture using Paperclip and S3, which is all working fine.

However, I want to add more file_fields to the same form for uploading several different images, because each article needs to have more than one picture.

I've been searching for the last three days and reading through some tutorials that seemed relevant, but usually just suggested using 'html: { multipart: true }' at the start of the form or on the file_field itself, but this just gave different versions of the same image, such as :medium, :thumb, :avatar. But I think I may not have been asking the question clearly enough...

Does anyone know how to achieve this functionality? If you can point me in the right direction or have any links that will help me to achieve this I will be so grateful that I will get down on my knees and hail you as a coding prophet.

Thank you all very much in advance.

Let me know if I haven't been clear enough... and thanks again.

How to parse pdf files to extract tables in them using Ruby?

Posted: 31 May 2016 03:16 AM PDT

I am doing some open source project, and improvising an already existing code. But I found these errors while executing them (pardon my below-basic knowledge on Ruby).

Class:

class Progress_bar    attr_accessor :items_to_do, :items_done      def initialize(items_to_do, items_done=0)      reset(items_to_do, items_done)    end      def percent_complete      return (@items_complete * 1.0 / @items_to_do * 1.0) * 100    end      def advance(steps_to_advance=1)      @items_complete += steps_to_advance    end      def reset(items_to_do, items_done=0)      @items_to_do    = items_to_do      @items_complete = items_done    end      def report      $stderr.print "\r#{progress_bar} #{@items_complete} of #{@items_to_do} done"    end      def clear      $stderr.print "\r" + " " * 100  + "\n"    end      def progress_bar      complete_bar   = (percent_complete / 2.0).floor      incomplete_bar = ((100 - percent_complete) / 2.0).ceil        return "[#{"*"*complete_bar}#{"-"*incomplete_bar}]"    end  end  

Module:

module Enumerable    def each_with_progress      progress = Progress_bar.new(self.size)        self.each do |item |        progress.advance        yield item        progress.report      end        progress.clear    end  end  

There's another program that calls this program, which is given below:

require_relative 'progress_bar.rb'  require 'pdf-reader'  require 'csv'    class Convert_pdf2csv    attr_accessor :max_cols, :result, :pagenum, :position      def initialize()      self.max_cols = 0      self.result = {}        self.pagenum = 0;      self.position = {        :current => [],        :prev    => []      }    end      public    def parsePDF(filename, encoding='UTF-8')      callbacks = reader(filename)        puts "parse reader callbacks"        callbacks.each_with_progress do |cb|        case cb[:name]        when  :'page='          @pagenum = cb[:args][0].number          @position = {            :current => [],            :prev    => []          }          when :show_text          x, y = @position[:current]            # assuming that the cell belonging to one logical line coincidentally to Y coordinates therefore, not to confuse the lines from different pages need to prefix the page number          row_key = @pagenum.to_s + '/' + y.to_s            @result[row_key]    ||= {}          @result[row_key][x] ||= ''            cell  = @result[row_key][x]            if cell.length > 0            cell += "\n"          end            value = cb[:args][0]            unless encoding == 'UTF-8'            value.encode!('UTF-8', encoding)          end            cell += value            max_cols = [@max_cols, @result[row_key].size].max            @result[row_key][x] = cell          when :move_text_position          @position[:prev]    = @position[:current]          @position[:current] = cb[:args]            # if the X coordinate of the previous value the same as the X coordinate of the next          # this is the next line of a multi- cell in the table          if (@position[:current][0] == @position[:prev][0])            @position[:current] = @position[:prev]          end          else          # ap cb[:name]        end      end    end    #assume that all lines have the same " width " in the logic table and everything else is just " the ornamental junk"        def generateCSV(filename, choose_only_wide_rows=true)      CSV.open(filename, "wb") do |csv|        puts "write csv file"          @result.each_with_progress do |row_key, row|          csvRow = []            if !choose_only_wide_rows || row.size == @max_cols            row.each do |cell_key, cell|              csvRow << cell            end              csv << csvRow          end        end      end    end      private    def reader(filename)      reader = PDF::Reader.new(filename)        receiver = PDF::Reader::RegisterReceiver.new        puts "read pdf pages"      reader.pages.each_with_progress do |page|        page.walk(receiver)      end      #We need to be combined into a single line for matching items from the neighboring positions Y      #if X is the same neighboring element and differs Y, it will transfer one cell line          receiver.callbacks    end  end  

The error that I'm getting is: C:/Ruby200-x64/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in require': cannot load such file -- pdf-reader (LoadError) from C:/Ruby200-x64/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:inrequire' from pdftocsv.rb:2:in `'

Can someone help me with this?

Sending hash values to controller from view

Posted: 31 May 2016 02:34 AM PDT

How do you send a @user hash to a controller? I'm trying to create a user from a view that already has some values in @customer to a "create" in a controller. But it's giving me undefined method `permit' for nil:NilClass for my params.require(...) I've looked around everywhere on this website as well as others and read books and have been working on it for 3 days now.. I'm a super newbie. Thanks in advance.

In my view:

link_to "Add User", users_path(@user), method: :post  

In my controller:

def user_params   params.require(:user).permit(:name, :email)  

Testing controller not passing parameter

Posted: 31 May 2016 04:08 AM PDT

Im currently working on my test cases for ruby on rails and realize that the parameter that i was passing is not being passed to my controller.

this is my test case for my controller

  test "should get addUser" do    user_info = User.create_user("TEST1","TEST1")    assert_equal(user_info,true,"Assert Failed")  

The User.create_user contains

def self.create_user(username,password)      if username == "" || password == "" and username == nil || password == nil          register = User.new({:username => username,:password => password})      end      return register.save  end  

the result also shows 2 assertions but i only declare one assert.

Webrick and thin both extreme slow

Posted: 31 May 2016 01:50 AM PDT

Ruby on rails development: My webrick server was running painfully slow even for loading normal html pages. I edited the config.rb file with :DoNotReverseLookup set to "true" but it was still slow. Installed gem 'thin' and ran thin as the default server. Its stilll equally or even more slow. Any help?

Service worker is not registering on chrome

Posted: 31 May 2016 02:09 AM PDT

I know service worker and push notification wont work without https SSL certificate so in my rails 3 app on dev environment i have setup self signed certificate for dev environment so all urls are opening with https. So now this service worker thing works on mozilla browser but its giving me following error on chrome

Service Worker error :^( DOMException: Failed to register a ServiceWorker: An SSL certificate error occurred when fetching the script.

Please help me with this.

render the view then call the existing AJAX view

Posted: 31 May 2016 02:52 AM PDT

I don't know how I am going to ask or start my question but what I want is to reuse my AJAX view to other page. I have an existing AJAX view, when I click a link from my sidebar I want to render a new page then call the AJAX view.

Please see example code below. I hope you understand my problem.

items_controller.rb

def index      @items = Item.all  end  

others_controller.rb

def category      @categories = Category.all  end  

views/items/index.html.erb

<%= @items.count %>  <div class="ajax_form"></div>  

views/others/category.js.erb

$(".ajax_form").html("<%= escape_javascript(render 'category') %>");  

views/others/category.html.erb

<%= @categories.count %>  

After I click the link from the sidebar, I want to call the ajax also without recreating it.

<a href="<%= items_path %>" >    click_me  </a>  

array usage inside rails remove duplicates

Posted: 31 May 2016 04:04 AM PDT

I've got this array coming back from a web scrape. Which looks like this:

[["formatted_sum_fees", "&Acirc;&pound;5.60"],   ["formatted_price", "&Acirc;&pound;46.50"],   ["formatted_sum_fees", "&Acirc;&pound;4.50"],   ["formatted_price", "&Acirc;&pound;37.50"],   ["formatted_sum_fees", "&Acirc;&pound;3.30"],   ["formatted_price", "&Acirc;&pound;27.50"],   ["formatted_sum_fees", "&Acirc;&pound;3.30"],   ["formatted_price", "&Acirc;&pound;27.50"],   ["formatted_sum_fees", "&Acirc;&pound;4.50"],   ["formatted_price", "&Acirc;&pound;37.50"],   ["formatted_sum_fees", "&Acirc;&pound;4.50"],   ["formatted_price", "&Acirc;&pound;37.50"],   ["formatted_sum_fees", "&Acirc;&pound;4.50"],   ["formatted_price", "&Acirc;&pound;37.50"],   ["formatted_sum_fees", "&Acirc;&pound;5.60"],   ["formatted_price", "&Acirc;&pound;46.50"],   ["formatted_sum_fees", "&Acirc;&pound;4.50"],   ["formatted_price", "&Acirc;&pound;37.50"],   ["formatted_sum_fees", "&Acirc;&pound;5.60"],   ["formatted_price", "&Acirc;&pound;46.50"],   ["formatted_sum_fees", "&Acirc;&pound;4.50"],   ["formatted_price", "&Acirc;&pound;37.50"],   ["formatted_sum_fees", "&Acirc;&pound;3.30"],   ["formatted_price", "&Acirc;&pound;27.50"]]  

So what happens is that it duplicates? So i'm wanting to change the above array to this (it will be different everytime so it'd need to remove duplicates.):

[["formatted_sum_fees", "&Acirc;&pound;5.60"],  ["formatted_price", "&Acirc;&pound;46.50"],  ["formatted_sum_fees", "&Acirc;&pound;4.50"],   ["formatted_price", "&Acirc;&pound;37.50"],  ["formatted_sum_fees", "&Acirc;&pound;3.30"],  ["formatted_price", "&Acirc;&pound;27.50"]  

Anything else that exists after this is a dupe.

What i'm needing is the fees and the price to be on a var so i can save it down to the database :)

Thanks Sam

extra Heres the raketask.

require "nokogiri"  require "open-uri"  namespace :task do    task test: :environment do      ticketmaster_url = "http://www.ticketmaster.co.uk/derren-brown-miracle-glasgow-04-07-2016/event/370050789149169E?artistid=1408737&majorcatid=10002&minorcatid=53&tpab=-1"       doc = Nokogiri::HTML(open(ticketmaster_url))       event_name = nil       ticket_price = nil       doc.xpath("//script[@type='text/javascript']/text()").each do |text|         if text.content =~ /more_options_on_polling/           ticket_price = text.to_s.scan(/\"(formatted_(?:price|sum_fees))\":\"(.+?)\"/)           byebug         end       end      end  end  

Monday, May 30, 2016

Ajax request not work rails 4 | Fixed issues

Ajax request not work rails 4 | Fixed issues


Ajax request not work rails 4

Posted: 30 May 2016 06:39 AM PDT

I am trying to hit the db at the exit of a field without reload the form using Ajax. The controller must do some process on the data obtained from the db and respond to the view. Then the user will continue with the input.

The following code is not working in my rails 4 app. I am missing something and just can't see what is wrong. I have the same piece of code working in a rails 3.2 application without problem.

In rails 3.2 the request go to check_matricula method, but in rails 4 go to show method in the controller.

Gemfile...

gem 'responders', '~> 2.0'

View...

<div class="field">      <%= f.text_field :matricula, { "data-remote" => true, "data-url" => "/liquidaciones_de_viajes/check_matricula", "data-type" => :json, :size => 10 } %>      <span id="check_matricula">&nbsp;</span>  </div>  

Controller...

class LiquidacionesDeViajesController < ApplicationController respond_to :html, :json

def check_matricula        @matricula = Matricula.find_by_codigo(params[:liquidacion_de_viajes][:matricula])      ... some process that result in matricula_ok true or false ...          if matricula_ok            respond_with(@matricula.empresa.razon_social)        else            respond_with(nil)        end    end  

assets/javascripts/check_matricula.js

$(document).ready(function() {      $("#liquidacion_de_viajes_matricula").bind('ajax:success', function(evt, data, status, xhr){          if (data !== null) {              $('#razon_social').html(data.razon_social);              $('#check_matricula').html('');          } else {              $('#check_matricula').html('Error de matricula');              $('#razon_social').empty();          }      });  $("#liquidacion_de_viajes_matricula").live('ajax:before', function(){      if ($(this).val() == '') {          return false;      }  });         $("#liquidacion_de_viajes_matricula").focus(function(){        $('#check_matricula').empty();        $('#razon_social').empty();    });    });  

ng token auth with rails devise user registration unpermitted parameters error

Posted: 30 May 2016 06:38 AM PDT

I have managed to set up ng-token-auth with ionic(angular) and devise-token-auth with rails however when I create a User an error is logged in the rails console even though the user is created.

In the console this shows up

Can't verify CSRF token authenticity  Unpermitted parameters: confirm_success_url, config_name, registration  Unpermitted parameters: confirm_success_url, config_name, registration  Unpermitted parameters: confirm_success_url, config_name, registration  

The user is created in the database however I have designed the ionic user controller to login the user once the registration is complete by using a promise. The controller is below:

comeDineApp.controller('userController', ['ipCookie','$scope', '$state', '$auth',  function(ipCookie, $scope, $state, $auth){      $scope.handleRegBtnClick = function() {      console.log("hello")      $auth.submitRegistration($scope.registrationForm)      .then(function() {        console.log("welcome")        $auth.submitLogin({          email: $scope.registrationForm.email,          password: $scope.registrationForm.password        });      });    };  }]);  

In this case the submitLogin function doesn't execute as the promise is not resolved even though the user is successfully created in the DB.

My rails user model is below:

class User < ActiveRecord::Base    # Include default devise modules.    devise :database_authenticatable, :registerable,    :recoverable, :rememberable, :trackable, :validatable,    :confirmable, :omniauthable    include DeviseTokenAuth::Concerns::User      has_many :tables        before_save -> do        self.uid = SecureRandom.uuid        skip_confirmation!      end    end  

and my user controller is:

class UsersController < ApplicationController      before_action :authenticate_user!    respond_to :json      def show      render json: current_user.tables    end  end  

Any ideas how I can resolve this either in the rails or the angular so that the error isn't presented and the angular promise resolves to login directly after signing up?

ruby on rails slim how to handle a value in select

Posted: 30 May 2016 06:27 AM PDT

I want to save the value of the option after submit .this a part of code (slim) but i can use also rubyon rails. please someone have any idea the select item is reference- brand- color- model- gender-ext_product_id

well.search-form  form  input type="hidden" value="put" name="_method"  - if search.scope == :my_items    input type="hidden" value="#{search_params.published}" name="published"    input type="hidden" value="#{search_params.query}" name="query"  fieldset    .row-fluid       .span8        label for="query" =translate"keyword"        select#query.selectoption name="keywordSearch"            option[value="reference" name="reference" selected=("selected" if @_source=="reference")] Reference           option[value="brand" name="brand" selected=("selected" if @_source=="brand")] Brand           option[value="model" name="model" selected=("selected" if @_source=="model")] Model           option[value="color" name="color"  selected=("selected" if @_source=="color")] Color           option[value="ext_product_id" name="ext_product_id" selected=("selected" if @_source=="ext_product_id")] Productid           option[value="gender" name="gender" selected=("selected" if @_source=="gender")] Gender  

Rescue exception thrown by a redirect_to :back

Posted: 30 May 2016 06:59 AM PDT

Little background information: I have a project with authenticated users which can have multiple 'scopes' of data. A scope determines which records can and can't be accessed by a user. A logged in user is always subsribed to a single scope stored in the session.

A user can at any time switch between the scopes he has access to, regardless of which page he is on.

After a scope switch I would like to try to reload the same page by using redirect_to :back. This is not always possible, since the current scope might not allow access to the page that was previously being viewed.

In those cases, the controller in question will throw an ActiveRecord::RecordNotFound exception in the respective controller on the .find(params[:id]) call, which is very ugly. I would very much like to gracefully fallback to a redirect_to :root with an accompanying alert message.

Currently I have this, but this does not work:

  def switch_scope      s = current_client.scopes.find(params[:scope_id])      set_scope(s.id)      begin        flash[:notice] = 'Scope switched succesfully.'        redirect_to :back # <= This might throw NotFoundException      rescue        flash[:alert] = 'Scope switched. Page could not be reloaded'        redirect_to :root      end    end  

Calculate NPS in Ruby

Posted: 30 May 2016 07:00 AM PDT

The net promoter score can have the values 0-10. It is divided in three groups:

Promoters = respondents giving a 9 or 10 score
Passives = respondents giving a 7 or 8 score
Detractors = respondents giving a 0 to 6 score

The score is calculated as the difference between the percentage of Promoters and Detractors.

Let's say we have the scores [10, 9, 10, 6, 2, 5, 10].

This would give the score +14 (57% - 43%).

I wish I could count occurrences of a range in an array, if that would be possible I would do

total_count = array.size  promoters = array.count(9..10)  passives = array.count(7..8)  detractors = array.count(0..6)    promoters_perc = promoters.to_f / total_count * 100  detractors_perc = detractors.to_f / total_count * 100    score = promoters_perc - detractors_perc  

How can I do this calculation?

Categories with Ancestry gem

Posted: 30 May 2016 06:21 AM PDT

I'm struggling a bit to wrap my head around the Ancestry gem. I'm trying to make categories which contain products.

I've got my current setup as follows:

  • Categories has the column ':ancestry, :string'
  • Categories model has the line 'has_ancestry'
  • Products model has nothing to do with Ancestry on it yet.

How do I go about actually putting products within certain categories? or is the set-up right for doing the following tree structure:

Category  - Product  - Product  - Product    Category  - Product  - Product  - Product  

Any help would be brilliant.

Active Model Serializers 0.10 exclude namespaces with JSON adapter?

Posted: 30 May 2016 06:36 AM PDT

Is there some way to exclude the namespace part of the model name in the root key?

I used Active Model Serializer version 0.9 before and my JSON representation of a User at localhost:3000/api/v1/users/1 was something like:

{ "user": { "id": 1, "first_name": "Foo", "last_name": "Bar" } }  

I recently upgraded to version 0.10 and now I get the namespace included in the root key:

{ "api/v1/user": { "id": 1,"first_name": "Foo", "last_name": "Bar" } }  

I want the root key to be like before, that is "user" instead of "api/v1/user".

web_1 | /docker-entrypoint.sh: line 99: exec: bundle: not found app_web_1 exited with code 127

Posted: 30 May 2016 05:50 AM PDT

I'm trying to use docker to push my existing rails project to a docker container.

I'm using postgres database.

When I did

docker-compose up

I get following error in the logs.

web_1  | /docker-entrypoint.sh: line 99: exec: bundle: not found  app_web_1 exited with code 127  

DokcerFile

FROM ruby:2.2.0  RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs  RUN mkdir /myapp  WORKDIR /myapp  ADD Gemfile /myapp/Gemfile  ADD Gemfile.lock /myapp/Gemfile.lock  RUN gem install bundler  RUN bundle install  ADD . /myapp    FROM postgres:9.4  #FROM library/postgres  ENV POSTGRES_USER my-user-name  ENV POSTGRES_PASSWORD ''  ENV POSTGRES_DB app-database-name  

docker-compose.yml

version: '2'  services:    db:      image: postgres    web:      build: .      command: bundle exec rails s -p 3000 -b '0.0.0.0'      volumes:        - .:/myapp      ports:        - "3000:3000"      depends_on:        - db  

What is `StringIO` in the context of RSpec testing (Ruby on Rails)?

Posted: 30 May 2016 06:55 AM PDT

What is StringIO in Ruby on Rails?

I'm trying to understand another SO answer that references StringIO, but its over my head.

I would suggest using StringIO for this and making sure your SUT accepts a stream to write to instead of a filename.

testIO = StringIO.new  sutObject.writeStuffTo testIO   testIO.string.should == "Hello, world!"  

Source: Rspec: how to test file operations and file content

Ruby-doc.org

Pseudo I/O on String object.

Source: http://ruby-doc.org/stdlib-1.9.3/libdoc/stringio/rdoc/StringIO.html)

Robots.thoughtbot

This is common in tests where we might inject a StringIO instead of reading an actual file from disk.

Source: https://robots.thoughtbot.com/io-in-ruby#stringio

My case:

File.open("data.dat", "wb") {|f| f.write(snapshot)}  

In my application I want to test the above, but I'm still confused how StringIO applies to implementing an RSpec test.

Could anyone with some experience in StringIO give some guidance?

Can't read data from hash using column(:) in rails

Posted: 30 May 2016 06:02 AM PDT

a = {"item"=>{"id"=>"34567", "name"=>"AAX item 1 Inventory23", "description"=>"AAX item 1 Inventory23", "unit_price"=>"2342", "item_type"=>"Inventory", "track_qty_on_hand"=>"true", "qty_on_hand"=>"50000", "inv_start_date"=>{"(3i)"=>"4", "(2i)"=>"5", "(1i)"=>"2016"}}, "company_id"=>"1", "item_type"=>"Inventory", "amount"=>"1232"}

Output:

a['item'] = {"id"=>"34567", "name"=>"AAX item 1 Inventory23", "description"=>"AAX item 1 Inventory23", "unit_price"=>"2342", "item_type"=>"Inventory", "track_qty_on_hand"=>"true", "qty_on_hand"=>"50000", "inv_start_date"=>{"(3i)"=>"4", "(2i)"=>"5", "(1i)"=>"2016"}}

a[:item] = nil

So, How to get data as a[:item]. What I have to change?

Rails server not starting in production mode

Posted: 30 May 2016 06:29 AM PDT

I want to start my rails server in production mode but it is exiting immediately.

rails server -e production  => Booting Thin  => Rails 4.1.4 application starting in production on http://0.0.0.0:3000  => Run `rails server -h` for more startup options  => Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)  => Ctrl-C to shutdown server  Thin web server (v1.6.4 codename Gob Bluth)  Maximum connections set to 1024  Listening on 0.0.0.0:3000, CTRL+C to stop  Exiting  

Performance issues when upgrading from ruby 1.9.3 to ruby 2.2.2

Posted: 30 May 2016 05:45 AM PDT

We have finally upgraded our app from ruby ruby-1.9.3-p545 to ruby-2.2.2. We are currently running rails 3.2

We have now subsequently encountered a 50% drop in performance. I am pretty suprised by this and not to sure where to start debugging. If anybody has any suggestions or experienced this pain before some advice would be much appreciated.

Ho do I specify how ActiveSupport::JSON.encode handles nested hash integer keys

Posted: 30 May 2016 05:54 AM PDT

I'm not sure if this is a bug, or if I'm missing an option to specify how to handle integer keys of nested hashes when converting to JSON using rails ActiveSupport::JSON.encode. Example of the problem

$ rails console  [deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.  Loading development environment (Rails 3.2.22.1)    Frame number: 0/5  [1] pry(main)> ActiveSupport::JSON.encode({outer: {1 => "a"}})  => "{\"outer\":{\"1\":\"a\"}}"  

As you can see, the inner hash key 1 has been converted to a string. I know there are various options to specify how to handle unknown classes/type and ActiveRecord specific things (like allowing joins with :include), but I would have thought that an integer as a 'native' type wouldn't require that sort of thing, and that nesting would be handled by default.

update join table has_many through with additional checkboxes

Posted: 30 May 2016 05:46 AM PDT

if i dont find solution here i have no idea where i should looking for...

I know there is right, easy solution for it...but something i just dont understand.

I have 3 models...

Scheme.rb

class Scheme < ActiveRecord::Base    has_many :projects    has_many :custom_issue_field_definitions, through: :scheme_custom_issue_field_definitions    has_many :scheme_custom_issue_field_definitions  end  

CustomIssueFieldDefinition.rb

class CustomIssueFieldDefinition < ActiveRecord::Base    has_many :schemes, through: :scheme_custom_issue_field_definitions    has_many :scheme_custom_issue_field_definitions    belongs_to :custom_issue_field  end  

SchemeCustomIssueFieldDefinition.rb

class SchemeCustomIssueFieldDefinition < ActiveRecord::Base    belongs_to :scheme    belongs_to :custom_issue_field_definition  end  

Join Model have 3 additional fields...with type: boolean.

enter image description here


I'd like to update scheme_custom_issue_field_definitions table. How controller and form should looks like?

Additional image: enter image description here

Update:

In console i can update it like this:

a = Scheme.first  b = CustomIssueFieldDefinition.first  c = a.scheme_custom_issue_field_defintitions.find_or_create_by(custom_issue_field_definition: b)  c.update_attributes(visible: 1, reportable: 0, required: 0)  

Next Update:

Now form looks like this (what is completely wrong):

<%= simple_form_for @scheme_new_custom_issue_field, url: configurations_scheme_path(@scheme), method: :put do |f| %>        <% @available_custom_issue_field_definitions.each do |custom_issue_field| %>          <tr>              <td><%= custom_issue_field.label %></td>              <td><%= f.input :visible, as: :boolean %></td>              <td><%= f.input :reportable, as: :boolean %></td>              <td><%= f.input :required, as: :boolean %></td>          </tr>        <% end %>        <%= f.button :submit, class: "btn btn-primary" %>      <% end %>   

and schemes_controller

def update      @scheme = Scheme.find(params[:id])      @scheme_new_custom_issue_field = @scheme.scheme_custom_issue_field_definitions.        find_or_create_by(scheme_id: @scheme, custom_issue_field_definition_id: params[:custom_issue_field_definition_id])      if @scheme_new_custom_issue_field.update_attributes(scheme_custom_issue_field_definition_params)        flash[:success] = "Scheme has been successfully updated"        redirect_to :back      else        render :edit      end    end  

How can I avoid the Post Processing in Paperclip

Posted: 30 May 2016 05:37 AM PDT

I use Paperclip for Document and Image Processing of both Tiff and PDF. So Tiff and PDF could be downloaded. Tiff should be converted to PDF and PDF should be left as it is. But when I download an PDF the Destination File has only one page. It seems like the Post Processing of Paperclip makes an automatic convert:

convert '/tmp/00c865a9d6c212a20cd851a448969f5520160530-4574-1yqdtq.pdf[0]' -auto-orient '/tmp/00c865a9d6c212a20cd851a448969f5520160530-4574-1yqdtq20160530-4574-8l8k7z.pdf'  

How can I avoid the Post Processing?

My Code:

has_mongoid_attached_file :document, styles: lambda { |a|    if a.instance.isTiff?    {      pdf: {        format: 'pdf',        processors: [:tiff_to_pdf]      }    }    else    {      pdf: {        format: 'pdf'      }    }  end  }  

Rails 4 - Devise :return_to previous url

Posted: 30 May 2016 05:45 AM PDT

In rails 4.2.4, I am using devise (3.5.6, 3.5.2, 3.2.4) gem. The scenario which should work for me is,

When user try to access user_profile_url(:anchor=>'section1') page from an email, it asks him to login, after login it leads to users_home_path. If he already logged in then it directly redirect to user_profile_url page(#section1).

How can I redirect to user_profile_url(:anchor=>'section1') as soon as session creates (clicked from email link)? I have tried to fix it by modifying after_sign_in_path_for(resource) method but it is not working.

def after_sign_in_path_for(resource)    session[:return_to] || users_home_path  end  

Please help me to solve this issue.

RoR: Cannot Migrate Database to Heroku

Posted: 30 May 2016 05:54 AM PDT

I am having trouble migrating my database to Heroku. I have checked the other issues that address this to no avail. I can really use a second pair of eyes on my code to help me figure this out.

This is the error I get:

rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    PG::UndefinedTable: ERROR:  relation "props" does not exist  : ALTER TABLE "comments" ADD CONSTRAINT "fk_rails_1d3f70cf04"  FOREIGN KEY ("prop_id")    REFERENCES "props" ("id")  

enter image description here

It seems to get caught while migrating this file:

class CreateComments < ActiveRecord::Migration    def change      create_table :comments do |t|        t.string :commenter        t.text :body        t.references :prop, index: true, foreign_key: true          t.timestamps null: false      end    end  end  

This is the migration file where I create the table props:

class CreateProps < ActiveRecord::Migration    def change      create_table :props do |t|        t.string :title        t.text :text        t.references :user, index: true, foreign_key: true          t.timestamps null: false      end    end  end  

My schema is here:

ActiveRecord::Schema.define(version: 20160528205746) do      # These are extensions that must be enabled in order to support this database    enable_extension "plpgsql"      create_table "answers", force: :cascade do |t|      t.string   "choice"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.string   "created_by"      t.integer  "user_id"      t.integer  "prop_id"    end      create_table "comments", force: :cascade do |t|      t.string   "commenter"      t.text     "body"      t.integer  "prop_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      add_index "comments", ["prop_id"], name: "index_comments_on_prop_id", using: :btree      create_table "props", force: :cascade do |t|      t.string   "title"      t.text     "text"      t.integer  "user_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.string   "choice"      t.string   "answer"      t.integer  "answerId"    end      add_index "props", ["user_id"], name: "index_props_on_user_id", using: :btree      create_table "user_answers", force: :cascade do |t|      t.integer  "user_id"      t.integer  "answer_id"      t.datetime "created_at"      t.datetime "updated_at"    end      create_table "users", force: :cascade do |t|      t.string   "username"      t.string   "email"      t.integer  "score",           default: 0      t.integer  "prop_id"      t.datetime "created_at",                      null: false      t.datetime "updated_at",                      null: false      t.string   "password_digest"      t.string   "created_by"      t.boolean  "admin",           default: false      t.integer  "answers_id"      t.integer  "answer_id"    end      add_index "users", ["answer_id"], name: "index_users_on_answer_id", using: :btree    add_index "users", ["prop_id"], name: "index_users_on_prop_id", using: :btree      create_table "wins", force: :cascade do |t|      t.string   "correctAnswer"      t.integer  "user_id"      t.datetime "created_at",    null: false      t.datetime "updated_at",    null: false    end      add_index "wins", ["user_id"], name: "index_wins_on_user_id", using: :btree      add_foreign_key "users", "answers"  end  

localhost issue for Ruby on Rails Existing Project, On a new project everything works fine

Posted: 30 May 2016 05:15 AM PDT

Ruby on rails can't connect to localhost after the server starts normally by typing rails s on console - boots using thin ... - Hosts file is fine .. - Created a new project and everything works fine with it .. - can't connect to localhost on Existing project(xyz) , no errors in log file .. - Same project runs fine on my other laptop. - tried for 127.0.0.1 and other ports

$ ruby -v  ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin15]  rails -v  Rails 4.2.1      $ telnet localhost 3000  Trying ::1...  telnet: connect to address ::1: Connection refused  Trying 127.0.0.1...  telnet: connect to address 127.0.0.1: Connection refused  telnet: Unable to connect to remote host  --------------------  

what do i do ? please help. Thanx in advance.

There was an error while trying to load the gem 'yard'

Posted: 30 May 2016 05:06 AM PDT

I am using sidekiq upstart job but while running sudo service sidekiq restart getting the following error

There was an error while trying to load the gem 'yard'.  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'  /home/ubuntu/.rvm/gems/ruby-2.2.1@myapp/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'  /home/ubuntu/myapp/config/application.rb:8:in `<top (required)>'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/sidekiq-3.2.5/lib/sidekiq/cli.rb:231:in `require'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/sidekiq-3.2.5/lib/sidekiq/cli.rb:231:in `boot_system'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/gems/2.2.0/gems/sidekiq-3.2.5/lib/sidekiq/cli.rb:49:in `run'  /home/ubuntu/.rvm/gems/ruby-2.2.1@global/gems/sidekiq-3.2.5/bin/sidekiq:8:in `<top (required)>'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/bin/sidekiq:23:in `load'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/bin/sidekiq:23:in `<main>'  

Following is the upstart job

/etc/init/sidekiq.conf

# /etc/init/sidekiq.conf - Sidekiq config    # This example config should work with Ubuntu 12.04+.  It  # allows you to manage multiple Sidekiq instances with  # Upstart, Ubuntu's native service management tool.  #  # See workers.conf for how to manage all Sidekiq instances at once.  #  # Save this config as /etc/init/sidekiq.conf then manage sidekiq with:  #   sudo start sidekiq index=0  #   sudo stop sidekiq index=0  #   sudo status sidekiq index=0  #  # Hack Upstart's reload command to 'quiet' Sidekiq:  #  #   sudo reload sidekiq index=0  #  # or use the service command:  #   sudo service sidekiq {start,stop,restart,status}  #    description "Sidekiq Background Worker"    # This script is not meant to start on bootup, workers.conf  # will start all sidekiq instances explicitly when it starts.  start on runlevel [2345]  stop on runlevel [06]    # change to match your deployment user   setuid ubuntu   setgid ubuntu      #respawn  #respawn limit 3 30    # TERM is sent by sidekiqctl when stopping sidekiq. Without declaring these as  # normal exit codes, it just respawns.  normal exit 0 TERM    # Older versions of Upstart might not support the reload command and need  # this commented out.  reload signal USR1    # Upstart waits 5 seconds by default to kill the a process. Increase timeout to  # give sidekiq process enough time to exit.  kill timeout 15    #instance $index    script  # this script runs in /bin/sh by default  # respawn as bash so we can source in rbenv  exec /bin/bash <<'EOT'    # Pick your poison :) Or none if you're using a system wide installed Ruby.      source /home/ubuntu/.bash_profile    source /home/ubuntu/.rvm/scripts/rvm    source /home/ubuntu/.bashrc    # Logs out to /var/log/upstart/sidekiq.log by default      cd /home/ubuntu/myapp/    exec bundle exec sidekiq -C config/sidekiq.yml -e production  EOT  end script  

How to get this working. I had also installed the gem yard but still getting the same error.

What is the best way to do Natural Language Processing in Rails app?

Posted: 30 May 2016 05:56 AM PDT

I have a Rails app. I need to implement automatic text categorization algorithms and possibly more NLP capabilities in app. I believe Ruby does not have good NLP tools available as Python has. I am using a separate resque server for process background jobs. I believe I have following

  1. Run python scripts using resque jobs
  2. Run a flask application on a separate server which can either talk to resque job or can automatically update the app database with processed results.
  3. Use Ruby tools mentioned in this thread
  4. Any other suggestions welcome

Please let me know what is the best way to do it. Are there any similar working examples?

ruby on rails many to many relationship views

Posted: 30 May 2016 06:10 AM PDT

i have created a many to many relationship between my phones table and accessories table using:

class Accessory    has_and_belongs_to_many :phones  end    class Phone    has_and_belongs_to_many :accessories  end  

I also implemented an intermediate table with and combined index of these tables ID's.

i am attempting to display two accessories for each phone which i have added in my seeds file.

This is code for my show.html - accessories

<div class="container">  

<% @accessories.each_slice(3) do |accessory| %>    <div class="row" >      <% accessory.each do |accessory| %>        <div class="col-lg-4" align="center">              <div id="img-box" , title="select image for more details ..." >            <% if not accessory.img_url.blank? %>              <%= link_to (image_tag accessory.img_url,:size => "200x160" ,class:"img-thumbnail" ),accessory %>              <% else %>                <%= link_to (image_tag("noimage.jpg",:size => "100x125")),accessory %>            <% end %>          </div>                <br/>                Name: <%= accessory.name %>                    Price: <%=  number_to_currency accessory.price, unit: "£"  %><br/>                    <td><%= link_to 'Edit', edit_accessory_path(@accessory) %> |  <%= link_to 'Back', accessories_path %>                </td>            <% end %>          </div>        </div>      <% end %>      </div>  <% end %>    </div>  

but i get the error :

show.html.erb:37: syntax error, unexpected keyword_ensure, expecting end-of-input

When removing <% end %> from a line, i then get the error:

undefined method `each_slice' for nil:NilClass

i have a link from a phone to the related accessory but wish to display more than one.

Thank you for any help :)

Rails nested form - refactor create action | cocoon gem

Posted: 30 May 2016 05:41 AM PDT

Everything is working fine but I want to change the code in create action to something like in update action. Right now, in the create action I am looping through all the values and saving them, but want to do it in a single line.

I have a College model.

class College< ActiveRecord::Base     has_many :staffs, dependent: :destroy     accepts_nested_attributes_for :staffs, reject_if: :all_blank, allow_destroy: true  end  

And this is my Staff.rb

class Staff < ActiveRecord::Base    belongs_to :college  end  

And these are my Staffs controller create and update actions

def create    @college= College.find(params[:college][:id_college_profile]    )    staff_params = params[:college][:staffs_attributes].values    staff_params.each do |staff_param|      @staff = @college.staffs.new      @staff.name = staff_param[:name]      @staff.designation = staff_param[:designation]      @staff.experience = staff_param[:experience]      @staff.specialization = staff_param[:specialization]      @staff.save    end    redirect_to dashboard_path(id: @college.id), notice: "Successfully added Staff."  end    def update    @college= College.find(params[:college][:id_college]    )    @college.update_attributes(staff_parameters)    redirect_to root_path  end  

These are strong parameters

def staff_parameters    params.require(:college).permit(:id, staffs_attributes: [:id,  :name, :specialization, :experience, :designation, :_destroy])  end  

Is there a way to save all of staffs in create action, without looping through all the values, but save all of them with a single line of code as in update action?

I have tried this in the StaffsController create action

def create    @college= College.find(params[:college][:id_college]    )    @staff= @college.staffs.new(staff_parameters)    @staff.save      redirect_to dashboard_path(id: @college.id), notice: "Successfully added Staffs."  end  

But it threw this error

unknown attribute 'staffs_attributes' for Staff.  

Can someone kindly help me with this issue?

How to pass authentication token in RSpec test for JSON API?

Posted: 30 May 2016 04:07 AM PDT

I'm trying to add an authorization token to an RSpec get JSON API test in Rails. But everything tried so far results in an error. The issue seems that the token is not being properly passed in the request.

expected the response to have a success status code (2xx) but it was 401  

Current code:

Project_spec.rb (tests)

before do      @project = create(:project, :key => "123")      get '/api/v1/projects/1', {:Authorization => "Token 123"}, format: :json  end    it "returns correct status" do      expect( response ).to have_http_status(:success)  end  

ProjectsController.rb

before_filter :restrict_access, :except => :create    def show      @project = Project.find(params[:id])      render json: @project  end    def restrict_access      authenticate_or_request_with_http_token do |token, options|          Project.exists?(key: token)      end  end  

Based on a few recommended solution found online, I've tried

  1. get '/api/v1/projects/1', format: :json, token: "123"

  2. get '/api/v1/projects/1', { 'HTTP-AUTHORIZATION' => 'Token "123"' }, format: :json

  3. get '/api/v1/projects/1', {:Authorization => "Token 123"}, format: :json

But nothing seems to successfully pass the authorization token.

Note: Style in #3 works when posting from an external application, but not in the RSpec test itself.

Does anyone have experience with this and can share some direction?

Load Balancing - Web Applications with NGINX

Posted: 30 May 2016 04:51 AM PDT

I have a web application ruby on rails who is not configured to multithreading. In nginx config, I set up an upstream block to be load balanced. Like this :

upstream myapp {    server 127.0.0.1:3075;    server 127.0.0.1:3076;    server 127.0.0.1:3077;  }  

I set up also 3 process thin with 3 ports (3075,3076,3077).

I think when my first application '127.0.0.1:3075' is busy, all the request will be balanced automatically to my second application '127.0.0.1:3076' or the third one.

But load balancing is not work, even though my three web applications are running correctly independent.

Where is my problème ? thank you for your reponse.

------------------- nginx config --------------------

upstream myapp_hosts {      server  127.0.0.1:3075;      server  127.0.0.1:3076;      server  127.0.0.1:3077;  }    server {      listen       80;      server_name  myapp.mydomain.com;      rewrite ^(.*)$ http://myapp.mydomain.com$1 permanent;      access_log /var/log/nginx/myapp.access.log;        location / {              proxy_pass         http://myapp_hosts/;              proxy_connect_timeout   900;              proxy_send_timeout      900;              proxy_read_timeout      900;              proxy_buffer_size   16k;              proxy_buffers       32   16k;              proxy_busy_buffers_size 64k;      }      location /public {              root /var/www/nemo/;        }      location /images {              root /var/www/nemo/assets/;        }      location /javascripts {              root /var/www/nemo/assets/;        }      location /stylesheets {              root /var/www/nemo/assets/;        }       client_max_body_size    10m;     client_body_buffer_size 128k;     client_header_buffer_size 64k;  }  

Access rails helpers methods inside presenter

Posted: 30 May 2016 04:00 AM PDT

I'm working on rails application, One of view page has lot of complex code, So moved logic to presenters but the problem I'm facing is not able to access helper methods inside the presenter.

Could any one help me to solve this issue, gone through the some SOF questions but it is not 'very' specific.

Cant we use include helper in the presenter or moving helper method into the presenter. which is the best way to approach this problem.

Errors when Deploying Rails app from my mac to vps server with Capistrano and Unicorn

Posted: 30 May 2016 03:33 AM PDT

I'm trying to deploy my rails app to VPS server with Capistrano and Unicorn but when I run (/etc/init.d/unicorn_app_name_env start) I got the following error

(/etc/init.d/unicorn_app_name: INIT_CONF: parameter not set)

SSHKit::Runner::ExecuteError: Exception while executing as deploy@IP... /etc/init.d/unicorn_app_name: INIT_CONF: parameter not set

What I should to solve this problem?

confusion in ruby on rails

Posted: 30 May 2016 03:26 AM PDT

I'm new in ruby on rails.Encountered a line

<span id="searchTab" class="<%=yield(:search_tab_id)%>"><%=link_to "Search", search_items_path %></span>  

what the line is doing exactly.

I want to implement another tab here named "XYZ" what are the steps I should follow.

what all things I have to add in controllers,views,routes etc

How to boost the closest created_at field in Elasticsearch?

Posted: 30 May 2016 05:19 AM PDT

I want to sort my query results following some boost rules and in the same time i want them to be sorted as possible by creation date, if i add a created_at sort, it changes everything and my results are not relevant anymore. So i guess the only way to do that is to boost created_at field (the newest has the biggest bonus in calculating score for that boost) but i dont know how to implement it. This is my query:

query = {    "query" : {      "bool" : {        "must" : [          {            "range" : {              "deadline" : {                "gte" : "2016-05-30T11:39:10+02:00"              }            }          },          {            "terms" : {              "state" : [                "open"              ]            }          },          {            "query_string" : {              "query" : "chant",              "default_operator" : "AND",              "analyzer" : "search_francais",              "fields" : [                "title^6",                "description",                "brand",                "category_name"              ]            }          }        ]      }    },    "filter" : {      "and" : [        {          "geo_distance" : {            "distance" : "40km",            "location" : {              "lat" : 48.855736,              "lon" : 2.32927300000006            }          }        }      ]    },    "sort" : [      {        "_score" : "desc"      },      #{      #  "created_at" : "desc"   ==> i tried this but it doesnt change results      #}    ]  }  

Create Excel file in Ruby on Rails with Axlsx

Posted: 30 May 2016 02:58 AM PDT

I try to create Excel files with the gem "axlsx". But i work for the first time with this gem and i try one Test.

I make one link_to to an controller action. There is no Error, but i didnt find a complete excel file.

Link_to :

<%= link_to "Test", { :controller => :orders, :action => :invoices_generate }, { class: "btn btn-primary btn-lg", style: "width: 100%;", format: 'xlsx'} %>  

My Controller :

def invoices_generate          respond_to do |format|      format.xlsx    end   end  

invoices_generate.xlsx.axlsx :

if examples.include? :basic    wb.add_worksheet(:name => "Basic Worksheet") do |sheet|      sheet.add_row ["First Column", "Second", "Third"]      sheet.add_row [1, 2, 3]      sheet.add_row ['     preserving whitespace']    end  end  

rails submit with diffrent values [loop] in nested forms

Posted: 30 May 2016 03:31 AM PDT

I am trying to deal in form with 2 level nested resource. My parrent resource is supplier. I've done adding (building) new descedants (address) in new ad edit form. I've also done adding (building) descedant of descedant (contacts) in new form but I have problem with adding descedant of descedant (contacts) in edit form. In edit form I want to add submit button [Add contact] after each contact and when user click on this button go to update method and build new contact instance in proper address -I need send with [Add contact] submit param with address ID. I have no idea how to do it. I've try hidden field but it send last hidden fiel value from loop. It is any chance to send diffrent param with submit button?

I have 2 level nested resource. Supplier has descedant -> address Address has descedant -> contact

Models: Supplier:

has_many :supplier_addresses     has_many :addresses, :through => :supplier_addresses     accepts_nested_attributes_for :addresses,                               :allow_destroy => true,                              :reject_if     => :all_blank    

Address:

has_many :address_contacts     has_many :contacts, :through => :address_contacts     accepts_nested_attributes_for :contacts,                               :allow_destroy => true,                              :reject_if     => :all_blank  

Contact:

 has_many :address_contacts     has_many :addresses, :through => :address_contacts  

Suppliers_Controller:

 class SuppliersController < ApplicationController       before_action :set_supplier, only: [:show, :edit, :update, :destroy]       def index        if params[:search]          @suppliers = Supplier.paginate(page: params[:page], :per_page => 15).by_letter(params[:search])           else          @suppliers = Supplier.paginate(page: params[:page], :per_page => 15).order(:name)        end     end      # GET /currencies/new    def new      @supplier = Supplier.new      ad=@supplier.addresses.build      ad.contacts.build    end      def show    end      def edit      ad=@supplier.addresses.build      ad.contacts.build    end       # POST /currencies    # POST /currencies.json    def create      @supplier = Supplier.new(supplier_params)      if add_address?        @supplier.addresses.build        respond_to do |format|          format.html { render :new }          format.json { render json: @supplier.errors, status: :unprocessable_entity }        end      elsif add_contact?        @supplier.addresses[params[:add_id].to_i].contacts.build        respond_to do |format|          format.html { render :new }          format.json { render json: @supplier.errors, status: :unprocessable_entity }        end      else        respond_to do |format|          if @supplier.save            flash[:info] = 'Supplier was successfully created.'            format.html { redirect_to @supplier }            format.json { render :show, status: :created, location: @supplier }          else            format.html { render :new }            format.json { render json: @supplier.errors, status: :unprocessable_entity }          end        end      end    end      # PATCH/PUT /currencies/1    # PATCH/PUT /currencies/1.json    def update      if add_address?        @supplier.addresses.build        respond_to do |format|          format.html { render :edit }          format.json { render json: @supplier.errors, status: :unprocessable_entity }        end      elsif add_contact?        @supplier.addresses[params[:add_id].to_i].contacts.build        respond_to do |format|          format.html { render :edit }          format.json { render json: @supplier.errors, status: :unprocessable_entity }        end      else        respond_to do |format|          if @supplier.update(supplier_params)            flash[:info] = 'Supplier was successfully updated.'            format.html { redirect_to supplier_url }            format.json { render :show, status: :ok, location: @supplier }          else            format.html { render :edit }            format.json { render json: @supplier.errors, status: :unprocessable_entity }          end        end      end    end      # DELETE /currencies/1    # DELETE /currencies/1.json    def destroy      @supplier.destroy      respond_to do |format|        flash[:info] = 'Supplier was successfully deleted.'        format.html { redirect_to suppliers_url }        format.json { head :no_content }      end    end       private      # Use callbacks to share common setup or constraints between actions.      def set_supplier        @supplier = Supplier.find(params[:id])      end        #for new add      def add_address?        params[:commit] == "Add address"      end        #for new add      def add_contact?        params[:commit] == "Add contact"      end        # Never trust parameters from the scary internet, only allow the white list through.      def supplier_params        params.require(:supplier).permit(:name, :notes, :min_order, :pay_terms,                                          addresses_attributes: [:id, :name, :street1, :street2, :county, :city, :country, :post_code, :_destroy,                                         contacts_attributes:[:id, :name, :job_title, :tel_no, :fax_no, :mobile_no, :email, :invoice_email, :contact_notes, :_destroy]])      end    end  

Form:

<%= form_for(@supplier) do |f| %>          <%= f.label :name %>        <%= f.text_field :name %>      <%= f.fields_for :addresses do |address| %>        <%= address.label :street %>      <%= address.text_field :street %>        <%= address.fields_for :contacts do |contact| %>        <%= contact.label :job_title %>      <%= contact.text_field :job_title %>        <%end%>        <%=hidden_field_tag params[:add_id], address.index%>      <div class="row">        <div class="actions text-center">          <%= f.submit  "Add contact",:class => 'btn btn-sm btn-warning custom2' %>        </div>      </div>      <%end%>      <div class="row">        <div class="actions text-center">          <%= f.submit "Add address",:class => 'btn btn-sm btn-warning custom2' %>          <%= f.submit :class => 'btn btn-sm btn-success custom2' %>        </div>      </div>    <%end%>