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  

No comments:

Post a Comment