Wednesday, July 13, 2016

Active Record Query 'where' to ignore spaces | Fixed issues

Active Record Query 'where' to ignore spaces | Fixed issues


Active Record Query 'where' to ignore spaces

Posted: 13 Jul 2016 08:04 AM PDT

How do I get all the records from db that match given string without spaces?

For example:

db record: "Hello beautiful world!"

given string: name = "Hello beau tifulworld !"

Is it possible to make it as Active Record Query?

Rails 5; Custom scaffold 'data type'?

Posted: 13 Jul 2016 08:04 AM PDT

It makes sense to do things like:

rails generate scaffold Agent name:string description:text alias:string artefacts:references`  

and

rails generate scaffold Artefact name:string content:text external_uuid:string agents:references`  

What I'm looking for now is to be able to specify things like:

agents:has_one  artefacts:has_many  attached_file:paperclipFile  

In this case, has_one is just a references data type with a change to the views, has_many is the same deal, but different changes, and paperclipFile would set up the model as well as the view with standard PaperClip boilerplate.

In Rails fashion, I expect that the supported data types are specified somewhere and can be overridden, but the question is how.


Caveat: I've noticed that for some reason the Rails scaffold generator doesn't get much love. It may be that everyone else knows a better way to do these things, but I have not run across it yet...

mongoid search by regex inccorect results

Posted: 13 Jul 2016 08:03 AM PDT

I try to search like in sql databases by LIKE only in mongo

here is my query

rooms = MessageRoom.order_by(:has_unread_messages => "desc").order_by(:updated_at => "desc").where(:user_name => /^#{params[:term]}/i)  

so the problem is every time I run this query I can obtain different results, sometimes not all of the results are in list and the order sometimes is different

Check if a value had already been updated by user

Posted: 13 Jul 2016 07:52 AM PDT

I have a user table. 2 questions :

  • When the user update his informations I would like to know if it's the first time he edit this field.
  • I would like to know if the edited information is not a former information.

Any ideas for doing that ?

Action Mailer is not run properly in rails

Posted: 13 Jul 2016 07:47 AM PDT

I am trying implementing send mail through action mailer in rails related code are..

initializer\setup_mail.rb

  ActionMailer::Base.smtp_settings = {  :address     =>"smtp.gmail.com",  :domain      =>"gmail.com",  :port        => 587,  :user_name   =>"Debasis",  :password    =>"************",  :authentication =>"plain",  :enable_starttls_auto =>true  }  

my mailers/user_mailer.rb

    class UserMailer < ActionMailer::Base       default :from => "bkdebasish90@gamil.com"       def registration_confirmation(user)         mail(:to=>user.email, :subject =>"Registered")          end            end  

and users.controller is

           def create      @user = User.new(user_params)          respond_to do |format|        if @user.save      UserMailer.registration_confirmation(@user).deliver          format.html { redirect_to @user, notice: 'User was successfully              created.' }         format.json { render :show, status: :created, location: @user }        else         format.html { render :new }      format.json { render json: @user.errors, status: :unprocessable_entity }      end     end     end  

my devlopment log is --

    UserMailer#registration_confirmation: processed outbound mail in 306.0ms         Sent mail to debasish.svin@gmail.com (2924.2ms)       Date: Wed, 13 Jul 2016 19:02:43 +0530        From: bkdebasish90@gamil.com         To: debasish.svin@gmail.com        Message-ID: <578642fb9cf1a_1b085217834727ad@debashis-PC.mail>        Subject: Registered       Mime-Version: 1.0      Content-Type: text/plain;      charset=UTF-8        Content-Transfer-Encoding: 7bit           Hi sir you signed in ....completed       Redirected to http://localhost:9292/users/18        Completed 302 Found in 3356ms (ActiveRecord: 86.0ms)  

and i see all are work fine.. but email is not come

Rails jquery on change doesn't work

Posted: 13 Jul 2016 07:43 AM PDT

I have simple script

 $ ->    $('.check__form').on 'change', ->      $('#filter_form').submit()  

but it work only when i reload page twice,on first load it doesn't work

How to fix it? or any advices what could cause this strange behavior

Adding default field such as timestamp to json when rendering in rails

Posted: 13 Jul 2016 07:41 AM PDT

I am newbie in Ruby on rails and want to config render :json, always adds an extra field such as timestamp or version at the end of json response. Like this

    {           //json data           "time_stamp" : 24312512341235      }  

I think it might have better way to do that than adding parameter everytime calling render json Thanks for helping

Rails - Adding random numbers at the end of a URL

Posted: 13 Jul 2016 08:07 AM PDT

I have this line to send a user to a specific page (www.uvestymeetings.com/) and I'm trying to have it generate a random number after the .com/ whenever a user submits. I'm thinking anywhere between 1-1000 is fine for now.

I know the random number on rails is : <%= rand(5..30) %>, but i'm not sure how to put it into this situation.

From controller:

respond_to do |format|    if @meeting.save      format.html { redirect_to 'https://www.uvestymeetings.com/', notice: "Thanks for meeting!" }      format.json { render action: 'show', status: :created, location: @meeting }    else      format.html { render action: 'new' }      format.json { render json: @meeting.errors, status: :unprocessable_entity }    end  end  

end

RVM switching Rails Versions

Posted: 13 Jul 2016 07:34 AM PDT

The situation is that my default gemset on my computer points to rails 5.0.0. However: I have an app that uses a really old rails version. Lets say for this example the app uses: rails 2.1.1.

Does my machine automatically switch to rails 2.1.1 when cd'ed into this app because rails 2.1.1 is specified in the Gemfile? Or: do I need to explicitly create a gemset in order for my app and my machine to do things the "rails 2.1.1 way" (as opposed to doing stuff the "rails 5.0.0 way which is the rails version in my default gemset)?

My concern is that perhaps if my machine thinks I am using rails 5.0.0 instead of rails 2.1.1 while developing inside the app: then rails commands such as generators might create files and do stuff "the rails 5.0.0 way" as opposed to the "rails 2.1.1" way.

Hopefully this makes sense. Here is what I would do in order to "explicitly" state via a Gemset that this app uses rails 2.1.1

Example:

I create a gemset that is to be specified for any app that uses rails 2.1.1

rvm gemset create rails_2_1_1  

I specify the ruby version to use on this gemset

rvm use 2.2.1@rails_2_1_1  

I then install that old version of rails onto this gemset:

gem install rails --version=2.1.1  

Now this gemset uses rails 2.1.1.

Now at the root of my app I specify a .ruby-gemset file that tells rails: "Make sure you are doing stuff the rails 2.1.1 way and not the rails 5.0.0 way:

#.ruby-gemset  rails_2_1_1  

I want to be sure that if another rails version is specified in an app's Gemfile than is in my default gemset: then developing within that app will do everything within the context of the rails version specified in the Gemfile as opposed to the rails version in the default gemset.

Rails app runs locally but crashes on Elastic Beanstalk

Posted: 13 Jul 2016 07:29 AM PDT

My RoR app tests out well locally. All tests created pass and the app functions as desired locally when tested with rails server as well as with passenger start.

Unfortunately, when the app is deployed to AWS EB and delegated one or more AWS EC2 instances, the instance(s) health immediately deteriorates to "degraded" and the auto-scaling/load balancer functionality (if activated) attempts to spin up more instances with the same result.

Visiting the Beanstalk Environment's URL just leads to a blank page (empty source code). I am not sure what to do.. I have identified a few lines from the below error log dump that I believe could be insightful but I have been unable to derive a solution from them:

2016/07/13 01:17:42 [error] 2880#0: *4 "/var/app/current/public/index.html" is not found (2: No such file or directory), client: 127.0.0.1, server: _, request: "HEAD / HTTP/1.1", host: "0.0.0.0"  2016/07/13 01:17:42 [error] 2880#0: *4 testing "/var/app/current/public" existence failed (2: No such file or directory) while logging request, client: 127.0.0.1, server: _, request: "HEAD / HTTP/1.1", host: "0.0.0.0"    ...    /opt/elasticbeanstalk/support/conf/nginx_config_healthd.erb:49:in `get_binding': undefined local variable or method `location_config_filename' for #<PhusionPassenger::Standalone::StartCommand:0x0055afae2de2c8> (NameError)  

Any help would be greatly appreciated!

Here is the full error log from Beanstalk:


    /var/app/support/logs/production.log      -------------------------------------      D, [2016-07-13T01:19:43.479025 #16079] DEBUG -- :   [1m[35m (4.4ms)[0m  [1m[35mCREATE TABLE "schema_migrations" ("version" varchar NOT NULL PRIMARY KEY)[0m      D, [2016-07-13T01:19:43.485867 #16079] DEBUG -- :   [1m[35m (5.5ms)[0m  [1m[35mCREATE TABLE "ar_internal_metadata" ("key" varchar NOT NULL PRIMARY KEY, "value" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)[0m      D, [2016-07-13T01:19:43.491581 #16079] DEBUG -- :   [1m[36mActiveRecord::SchemaMigration Load (0.1ms)[0m  [1m[34mSELECT "schema_migrations".* FROM "schema_migrations"[0m      I, [2016-07-13T01:19:43.493839 #16079]  INFO -- : Migrating to CreateLaunchSubscribers (20160711012123)      D, [2016-07-13T01:19:43.495026 #16079] DEBUG -- :   [1m[35m (0.0ms)[0m  [1m[36mbegin transaction[0m      D, [2016-07-13T01:19:43.495994 #16079] DEBUG -- :   [1m[35m (0.2ms)[0m  [1m[35mCREATE TABLE "launch_subscribers" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar, "email" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)[0m      D, [2016-07-13T01:19:43.499129 #16079] DEBUG -- :   [1m[35mSQL (0.1ms)[0m  [1m[32mINSERT INTO "schema_migrations" ("version") VALUES (?)[0m  [["version", "20160711012123"]]      D, [2016-07-13T01:19:43.509943 #16079] DEBUG -- :   [1m[35m (10.7ms)[0m  [1m[36mcommit transaction[0m      D, [2016-07-13T01:19:43.511887 #16079] DEBUG -- :   [1m[36mActiveRecord::InternalMetadata Load (0.1ms)[0m  [1m[34mSELECT  "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = ? LIMIT ?[0m  [["key", :environment], ["LIMIT", 1]]      D, [2016-07-13T01:19:43.518319 #16079] DEBUG -- :   [1m[35m (0.1ms)[0m  [1m[36mbegin transaction[0m      D, [2016-07-13T01:19:43.519147 #16079] DEBUG -- :   [1m[35mSQL (0.1ms)[0m  [1m[32mINSERT INTO "ar_internal_metadata" ("key", "value", "created_at", "updated_at") VALUES (?, ?, ?, ?)[0m  [["key", "environment"], ["value", "production"], ["created_at", 2016-07-13 01:19:43 UTC], ["updated_at", 2016-07-13 01:19:43 UTC]]      D, [2016-07-13T01:19:43.567003 #16079] DEBUG -- :   [1m[35m (47.7ms)[0m  [1m[36mcommit transaction[0m            -------------------------------------      /var/app/support/logs/passenger.log      -------------------------------------      [ 2016-07-13 01:17:39.2862 2860/7f0f1ef76780 agents/Watchdog/Main.cpp:538 ]: Options: { 'analytics_log_user' => 'webapp', 'cleanup_pidfiles' => 'L3RtcC9wYXNzZW5nZXItc3RhbmRhbG9uZS5veGQ4amEvdGVtcF9kaXJfdG91Y2hlci5waWQ=', 'default_group' => 'webapp', 'default_python' => 'python', 'default_ruby' => '/opt/rubies/ruby-2.3.1/bin/ruby', 'default_user' => 'webapp', 'log_level' => '0', 'max_pool_size' => '6', 'passenger_root' => '/tmp/passenger-standalone.oxd8ja/locations.ini', 'passenger_version' => '4.0.60', 'pool_idle_time' => '300', 'prestart_urls' => 'aHR0cDovLzAuMC4wLjA6ODAA', 'temp_dir' => '/tmp', 'union_station_gateway_address' => 'gateway.unionstationapp.com', 'union_station_gateway_port' => '443', 'user_switching' => 'false', 'web_server_passenger_version' => '4.0.60', 'web_server_pid' => '2859', 'web_server_type' => 'nginx', 'web_server_worker_gid' => '495', 'web_server_worker_uid' => '497' }      [ 2016-07-13 01:17:40.3992 2863/7f3cb4136780 agents/HelperAgent/Main.cpp:650 ]: PassengerHelperAgent online, listening at unix:/tmp/passenger.1.0.2859/generation-0/request      [ 2016-07-13 01:17:40.8989 2871/7f99ca27c840 agents/LoggingAgent/Main.cpp:321 ]: PassengerLoggingAgent online, listening at unix:/tmp/passenger.1.0.2859/generation-0/logging      [ 2016-07-13 01:17:40.8991 2860/7f0f1ef76780 agents/Watchdog/Main.cpp:728 ]: All Phusion Passenger agents started!      2016/07/13 01:17:42 [error] 2880#0: *4 "/var/app/current/public/index.html" is not found (2: No such file or directory), client: 127.0.0.1, server: _, request: "HEAD / HTTP/1.1", host: "0.0.0.0"      2016/07/13 01:17:42 [error] 2880#0: *4 testing "/var/app/current/public" existence failed (2: No such file or directory) while logging request, client: 127.0.0.1, server: _, request: "HEAD / HTTP/1.1", host: "0.0.0.0"            -------------------------------------      /var/log/eb-activity.log      -------------------------------------        memory. However your system only has 995 MB of total virtual memory (995 MB        RAM, 0 MB swap). It is recommended that you temporarily add more swap space        before proceeding. You can do it as follows:            sudo dd if=/dev/zero of=/swap bs=1M count=1024          sudo mkswap /swap          sudo swapon /swap          See also https://wiki.archlinux.org/index.php/Swap for more information about        the swap file on Linux.          If you cannot activate a swap file (e.g. because you're on OpenVZ, or if you        don't have root privileges) then you should install Phusion Passenger through        DEB/RPM packages. For more information, please refer to our installation        documentation:            https://www.phusionpassenger.com/library/install/standalone/          Press Ctrl-C to abort this installer (recommended).        Press Enter if you want to continue with installation anyway.        Checking for required software...           [1m* Checking for C compiler...[0m[37m[40m              Found: [1m[32myes[0m[37m[40m              Location: /usr/bin/cc         [1m* Checking for C++ compiler...[0m[37m[40m              Found: [1m[32myes[0m[37m[40m              Location: /usr/bin/c++         [1m* Checking for GNU make...[0m[37m[40m              Found: [1m[32myes[0m[37m[40m              Location: /usr/bin/gmake         [1m* Checking for Rake (associated with /opt/rubies/ruby-2.3.1/bin/ruby)...[0m[37m[40m              Found: [1m[32myes[0m[37m[40m              Location: /opt/rubies/ruby-2.3.1/bin/ruby /opt/rubies/ruby-2.3.1/bin/rake         [1m* Checking for OpenSSL development headers...[0m[37m[40m              Found: [1m[32myes[0m[37m[40m              Location: /usr/include/openssl/ssl.h         [1m* Checking for Zlib development headers...[0m[37m[40m              Found: [1m[32myes[0m[37m[40m              Location: /usr/include/zlib.h         [1m* Checking for PCRE development headers...[0m[37m[40m              Found: [1m[32myes[0m[37m[40m              Location: /usr/include/pcre.h          Installing...        Downloading Nginx 1.8.1 source code...        Extracting tarball...        Compiling support libraries (step 1 of 2)...        ......................................................................................................................................................................................................................................................................................................................................        Compiling Nginx engine (step 2 of 2)...        ...................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................        Compilation finished!          --------------------------           [passenger_native_support.so] trying to compile for the current user (root) and Ruby interpreter...             (set PASSENGER_COMPILE_NATIVE_SUPPORT_BINARY=0 to disable)             Compilation successful. The logs are here:             /tmp/passenger_native_support-1qzggon.log         [passenger_native_support.so] successfully loaded.        /opt/elasticbeanstalk/support/conf/nginx_config_healthd.erb:49:in `get_binding': undefined local variable or method `location_config_filename' for #<PhusionPassenger::Standalone::StartCommand:0x0055afae2de2c8> (NameError)          from /opt/rubies/ruby-2.3.1/lib/ruby/2.3.0/erb.rb:864:in `eval'          from /opt/rubies/ruby-2.3.1/lib/ruby/2.3.0/erb.rb:864:in `result'          from /opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.0.29/src/ruby_supportlib/phusion_passenger/standalone/start_command/nginx_engine.rb:177:in `block in write_nginx_config_file'          from /opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.0.29/src/ruby_supportlib/phusion_passenger/standalone/start_command/nginx_engine.rb:170:in `open'          from /opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.0.29/src/ruby_supportlib/phusion_passenger/standalone/start_command/nginx_engine.rb:170:in `write_nginx_config_file'          from /opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.0.29/src/ruby_supportlib/phusion_passenger/standalone/start_command/nginx_engine.rb:41:in `start_engine_real'          from /opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.0.29/src/ruby_supportlib/phusion_passenger/standalone/start_command.rb:322:in `start_engine'          from /opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.0.29/src/ruby_supportlib/phusion_passenger/standalone/start_command.rb:63:in `run'          from /opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.0.29/src/ruby_supportlib/phusion_passenger/standalone/main.rb:51:in `run!'          from /opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0/gems/passenger-5.0.29/bin/passenger:45:in `<top (required)>'          from /opt/rubies/ruby-2.3.1/bin/passenger:23:in `load'          from /opt/rubies/ruby-2.3.1/bin/passenger:23:in `<main>'      [2016-07-13T01:21:12.939Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/StartupStage1/AppDeployEnactHook] : Completed activity. Result:        Successfully execute hooks in directory /opt/elasticbeanstalk/hooks/appdeploy/enact.      [2016-07-13T01:21:12.939Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/StartupStage1/AppDeployPostHook] : Starting activity...      [2016-07-13T01:21:12.939Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/StartupStage1/AppDeployPostHook/01_create_pids.sh] : Starting activity...      [2016-07-13T01:21:43.111Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/StartupStage1/AppDeployPostHook/01_create_pids.sh] : Completed activity.      [2016-07-13T01:21:43.111Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/StartupStage1/AppDeployPostHook] : Completed activity. Result:        Successfully execute hooks in directory /opt/elasticbeanstalk/hooks/appdeploy/post.      [2016-07-13T01:21:43.112Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/StartupStage1/PostInitHook] : Starting activity...      [2016-07-13T01:21:43.112Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/StartupStage1/PostInitHook] : Completed activity. Result:        Successfully execute hooks in directory /opt/elasticbeanstalk/hooks/postinit.      [2016-07-13T01:21:43.112Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/StartupStage1] : Completed activity. Result:        Application deployment - Command CMD-Startup stage 1 completed      [2016-07-13T01:21:43.112Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/AddonsAfter] : Starting activity...      [2016-07-13T01:21:43.112Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/AddonsAfter/ConfigLogRotation] : Starting activity...      [2016-07-13T01:21:43.112Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/AddonsAfter/ConfigLogRotation/10-config.sh] : Starting activity...      [2016-07-13T01:21:43.233Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/AddonsAfter/ConfigLogRotation/10-config.sh] : Completed activity. Result:        Disabled forced hourly log rotation.      [2016-07-13T01:21:43.233Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/AddonsAfter/ConfigLogRotation] : Completed activity. Result:        Successfully execute hooks in directory /opt/elasticbeanstalk/addons/logpublish/hooks/config.      [2016-07-13T01:21:43.233Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1/AddonsAfter] : Completed activity.      [2016-07-13T01:21:43.233Z] INFO  [2975]  - [Application deployment app-7e88-160712_211417@1] : Completed activity. Result:        Application deployment - Command CMD-Startup succeeded      [2016-07-13T01:23:36.190Z] INFO  [19057] - [CMD-TailLogs] : Starting activity...      [2016-07-13T01:23:36.190Z] INFO  [19057] - [CMD-TailLogs/AddonsBefore] : Starting activity...      [2016-07-13T01:23:36.190Z] INFO  [19057] - [CMD-TailLogs/AddonsBefore] : Completed activity.      [2016-07-13T01:23:36.190Z] INFO  [19057] - [CMD-TailLogs/TailLogs] : Starting activity...      [2016-07-13T01:23:36.190Z] INFO  [19057] - [CMD-TailLogs/TailLogs/TailLogs] : Starting activity...            -------------------------------------      /var/app/support/logs/access.log      -------------------------------------      127.0.0.1 - - [13/Jul/2016:01:17:42 +0000] "HEAD / HTTP/1.1" 404 0 "-" "-"            -------------------------------------      /var/log/eb-commandprocessor.log      -------------------------------------      [2016-07-13T01:17:01.594Z] DEBUG [2632]  : Refreshing metadata...      [2016-07-13T01:17:01.597Z] DEBUG [2632]  : Using cached environment metadata.      [2016-07-13T01:17:01.597Z] DEBUG [2632]  : Retrieving metadata for key: AWS::ElasticBeanstalk::Ext||_ContainerConfigFileContent||commands..      [2016-07-13T01:17:01.598Z] DEBUG [2632]  : Retrieving metadata for key: AWS::ElasticBeanstalk::Ext||_API||_Commands..      [2016-07-13T01:17:01.598Z] INFO  [2632]  : Found enabled addons: ["logpublish"].      [2016-07-13T01:17:01.598Z] INFO  [2632]  : Updating Command definition of addon logpublish.      [2016-07-13T01:17:01.599Z] DEBUG [2632]  : Retrieving metadata for key: AWS::CloudFormation::Init||Infra-WriteApplication2||files..      [2016-07-13T01:17:01.601Z] DEBUG [2632]  : Retrieving metadata for key: AWS::ElasticBeanstalk::Ext||ManifestFileS3Key..      [2016-07-13T01:17:02.199Z] INFO  [2632]  : Finding latest manifest from bucket 'elasticbeanstalk-us-west-2-615201702363' with prefix 'resources/environments/e-n35dn7ryje/_runtime/versions/manifest_'.      [2016-07-13T01:17:02.732Z] INFO  [2632]  : Found manifest with key 'resources/environments/e-n35dn7ryje/_runtime/versions/manifest_1468372471196'.      [2016-07-13T01:17:02.794Z] INFO  [2632]  : Updated manifest cache: deployment ID 1 and serial 1.      [2016-07-13T01:17:02.794Z] DEBUG [2632]  : Loaded definition of Command CMD-PreInit.      [2016-07-13T01:17:02.795Z] INFO  [2632]  : Executing Initialization      [2016-07-13T01:17:02.795Z] INFO  [2632]  : Executing command: CMD-PreInit...      [2016-07-13T01:17:02.795Z] INFO  [2632]  : Executing command CMD-PreInit activities...      [2016-07-13T01:17:02.795Z] DEBUG [2632]  : Setting environment variables..      [2016-07-13T01:17:02.795Z] INFO  [2632]  : Running AddonsBefore for command CMD-PreInit...      [2016-07-13T01:17:02.795Z] DEBUG [2632]  : Running stages of Command CMD-PreInit from stage 0 to stage 0...      [2016-07-13T01:17:02.795Z] INFO  [2632]  : Running stage 0 of command CMD-PreInit...      [2016-07-13T01:17:02.795Z] DEBUG [2632]  : Loaded 3 actions for stage 0.      [2016-07-13T01:17:02.795Z] INFO  [2632]  : Running 1 of 3 actions: InfraWriteConfig...      [2016-07-13T01:17:02.797Z] INFO  [2632]  : Running 2 of 3 actions: DownloadSourceBundle...      [2016-07-13T01:17:03.175Z] INFO  [2632]  : Running 3 of 3 actions: PreInitHook...      [2016-07-13T01:17:41.091Z] INFO  [2632]  : Running AddonsAfter for command CMD-PreInit...      [2016-07-13T01:17:41.091Z] INFO  [2632]  : Command CMD-PreInit succeeded!      [2016-07-13T01:17:41.091Z] INFO  [2632]  : Command processor returning results:       {"status":"SUCCESS","api_version":"1.0","results":[{"status":"SUCCESS","msg":"","returncode":0,"events":[]}]}      [2016-07-13T01:17:57.387Z] DEBUG [2975]  : Reading config file: /etc/elasticbeanstalk/.aws-eb-stack.properties      [2016-07-13T01:17:57.387Z] DEBUG [2975]  : Checking if the command processor should execute...      [2016-07-13T01:17:57.390Z] DEBUG [2975]  : Checking whether the command is applicable to instance (i-07977d6c52f370f9d)..      [2016-07-13T01:17:57.390Z] INFO  [2975]  : Command is applicable to this instance (i-07977d6c52f370f9d)..      [2016-07-13T01:17:57.390Z] DEBUG [2975]  : Checking if the received command stage is valid..      [2016-07-13T01:17:57.390Z] INFO  [2975]  : No stage_num in command. Valid stage..      [2016-07-13T01:17:57.390Z] INFO  [2975]  : Received command CMD-Startup: {"execution_data":"{\"leader_election\":\"true\"}","instance_ids":["i-07977d6c52f370f9d"],"command_name":"CMD-Startup","api_version":"1.0","resource_name":"AWSEBAutoScalingGroup","request_id":"2237ea1b-4897-11e6-8db9-ad2a7159939a","command_timeout":"600"}      [2016-07-13T01:17:57.390Z] INFO  [2975]  : Command processor should execute command.      [2016-07-13T01:17:57.390Z] DEBUG [2975]  : Storing current stage..      [2016-07-13T01:17:57.390Z] DEBUG [2975]  : Stage_num does not exist. Not saving null stage. Returning..      [2016-07-13T01:17:57.390Z] DEBUG [2975]  : Reading config file: /etc/elasticbeanstalk/.aws-eb-stack.properties      [2016-07-13T01:17:57.390Z] DEBUG [2975]  : Retrieving metadata for key: AWS::ElasticBeanstalk::Ext||_ContainerConfigFileContent||commands..      [2016-07-13T01:17:57.390Z] DEBUG [2975]  : Retrieving metadata for key: AWS::ElasticBeanstalk::Ext||_API||_Commands..      [2016-07-13T01:17:57.391Z] INFO  [2975]  : Found enabled addons: ["logpublish"].      [2016-07-13T01:17:57.392Z] INFO  [2975]  : Updating Command definition of addon logpublish.      [2016-07-13T01:17:57.392Z] DEBUG [2975]  : Refreshing metadata...      [2016-07-13T01:17:57.640Z] DEBUG [2975]  : Refreshed environment metadata.      [2016-07-13T01:17:57.640Z] DEBUG [2975]  : Retrieving metadata for key: AWS::ElasticBeanstalk::Ext||_ContainerConfigFileContent||commands..      [2016-07-13T01:17:57.641Z] DEBUG [2975]  : Retrieving metadata for key: AWS::ElasticBeanstalk::Ext||_API||_Commands..      [2016-07-13T01:17:57.641Z] INFO  [2975]  : Found enabled addons: ["logpublish"].      [2016-07-13T01:17:57.642Z] INFO  [2975]  : Updating Command definition of addon logpublish.      [2016-07-13T01:17:57.642Z] DEBUG [2975]  : Loaded definition of Command CMD-Startup.      [2016-07-13T01:17:57.642Z] INFO  [2975]  : Executing Application deployment      [2016-07-13T01:17:57.643Z] INFO  [2975]  : Executing command: CMD-Startup...      [2016-07-13T01:17:57.643Z] INFO  [2975]  : Executing command CMD-Startup activities...      [2016-07-13T01:17:57.643Z] DEBUG [2975]  : Setting environment variables..      [2016-07-13T01:17:57.643Z] INFO  [2975]  : Running AddonsBefore for command CMD-Startup...      [2016-07-13T01:17:57.643Z] DEBUG [2975]  : Running stages of Command CMD-Startup from stage 0 to stage 1...      [2016-07-13T01:17:57.643Z] INFO  [2975]  : Running stage 0 of command CMD-Startup...      [2016-07-13T01:17:57.643Z] INFO  [2975]  : Running leader election...      [2016-07-13T01:17:57.887Z] INFO  [2975]  : Instance is Leader.      [2016-07-13T01:17:57.887Z] DEBUG [2975]  : Loaded 7 actions for stage 0.      [2016-07-13T01:17:57.887Z] INFO  [2975]  : Running 1 of 7 actions: HealthdLogRotation...      [2016-07-13T01:17:57.892Z] INFO  [2975]  : Running 2 of 7 actions: HealthdHTTPDLogging...      [2016-07-13T01:17:57.892Z] INFO  [2975]  : Running 3 of 7 actions: HealthdNginxLogging...      [2016-07-13T01:17:57.892Z] INFO  [2975]  : Running 4 of 7 actions: EbExtensionPreBuild...      [2016-07-13T01:17:58.164Z] INFO  [2975]  : Running 5 of 7 actions: AppDeployPreHook...      [2016-07-13T01:19:43.583Z] INFO  [2975]  : Running 6 of 7 actions: EbExtensionPostBuild...      [2016-07-13T01:19:43.856Z] INFO  [2975]  : Running 7 of 7 actions: InfraCleanEbExtension...      [2016-07-13T01:19:43.860Z] INFO  [2975]  : Running stage 1 of command CMD-Startup...      [2016-07-13T01:19:43.860Z] DEBUG [2975]  : Loaded 3 actions for stage 1.      [2016-07-13T01:19:43.860Z] INFO  [2975]  : Running 1 of 3 actions: AppDeployEnactHook...      [2016-07-13T01:21:12.939Z] INFO  [2975]  : Running 2 of 3 actions: AppDeployPostHook...      [2016-07-13T01:21:43.111Z] INFO  [2975]  : Running 3 of 3 actions: PostInitHook...      [2016-07-13T01:21:43.112Z] INFO  [2975]  : Running AddonsAfter for command CMD-Startup...      [2016-07-13T01:21:43.233Z] INFO  [2975]  : Command CMD-Startup succeeded!      [2016-07-13T01:21:43.233Z] INFO  [2975]  : Command processor returning results:       {"status":"SUCCESS","api_version":"1.0","results":[{"status":"SUCCESS","msg":"","returncode":0,"events":[]}]}      [2016-07-13T01:23:36.184Z] DEBUG [19057] : Reading config file: /etc/elasticbeanstalk/.aws-eb-stack.properties      [2016-07-13T01:23:36.184Z] DEBUG [19057] : Checking if the command processor should execute...      [2016-07-13T01:23:36.187Z] DEBUG [19057] : Checking whether the command is applicable to instance (i-07977d6c52f370f9d)..      [2016-07-13T01:23:36.187Z] INFO  [19057] : Command is applicable to this instance (i-07977d6c52f370f9d)..      [2016-07-13T01:23:36.187Z] DEBUG [19057] : Checking if the received command stage is valid..      [2016-07-13T01:23:36.187Z] INFO  [19057] : No stage_num in command. Valid stage..      [2016-07-13T01:23:36.187Z] INFO  [19057] : Received command CMD-TailLogs: {"execution_data":"{\"aws_access_key_id\":\"ASIAJVMOQJRPGLVNY52Q\",\"signature\":\"TTpp6MvoQzmJMyFtEvAHzKJt0I0=\",\"security_token\":\"FQoDYXdzEFMaDJS2KY9kvCnSjUKYdiKtA5HQ2JgqmYPHhSwQof5rs1Zh+a3kNYs3SWbtHBaFWWxqgI67bgJe3+zRr+yI3YoMsTVkqU6Bw+sOiZvXHHaGK7lTDiIDh2rMV8V+UVpFuF0MBt3EJA6oe34fpW6uuqmqwUOl1O644ZJ7InhFFR7dmjAcdO10YQCCX4YF9j6sNDsv6YJpnrlqye9\\\/mwNOvQjXgHGJP5T4gjvPTpCjdQhscYvN9tV8xzPD8BSl\\\/xXHVOlRmUzeow5oGeEhmuiX3JbNM7BDFGYpOIG\\\/hgv44RpkM4aid4\\\/bTjSiZ9yYh+O8YN7QmKZ1MpJGQsy3OiroUutjEzJnuKUWJam9Xsl4ND80OKi9HWxaFd2O\\\/gNWCxg4j3+1cCFGSrQfL5c4lveDcH8JLakxeIcT2rsRUj3PBgp4fLu+YK7X9ThhXzzDNs4KLtV1feWYw1PWJsZ0OudXRYmrAerCtd3ojU0jcD47VcB0vt83EN+5dUHY0s4FCwodDo0C6e3F6tCCy5DS8rLa9g3yTZMTRQFxWIPRSSnrUUNqu3pUS\\\/vffWXSds0J+t5oAwXp6uSg4A2FTG8rEg1qfiic4JO8BQ==\",\"policy\":\"eyJleHBpcmF0aW9uIjoiMjAxNi0wNy0xM1QwMTo1MzozNC4yNTRaIiwiY29uZGl0aW9ucyI6W1sic3RhcnRzLXdpdGgiLCIkeC1hbXotbWV0YS10aW1lX3N0YW1wIiwiIl0sWyJzdGFydHMtd2l0aCIsIiR4LWFtei1tZXRhLXB1Ymxpc2hfbWVjaGFuaXNtIiwiIl0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJyZXNvdXJjZXNcL2Vudmlyb25tZW50c1wvbG9nc1wvIl0sWyJzdGFydHMtd2l0aCIsIiR4LWFtei1tZXRhLWJhdGNoX2lkIiwiIl0sWyJzdGFydHMtd2l0aCIsIiR4LWFtei1tZXRhLWZpbGVfbmFtZSIsIiJdLFsic3RhcnRzLXdpdGgiLCIkeC1hbXotc2VjdXJpdHktdG9rZW4iLCIiXSxbInN0YXJ0cy13aXRoIiwiJENvbnRlbnQtVHlwZSIsIiJdLFsiZXEiLCIkYnVja2V0IiwiZWxhc3RpY2JlYW5zdGFsay11cy13ZXN0LTItNjE1MjAxNzAyMzYzIl0sWyJlcSIsIiRhY2wiLCJwcml2YXRlIl1dfQ==\"}","instance_ids":["i-07977d6c52f370f9d"],"data":"6a7bb5b4-4898-11e6-a3c3-37a522e81ab8","command_name":"CMD-TailLogs","api_version":"1.0","resource_name":"AWSEBAutoScalingGroup","request_id":"6a7bb5b4-4898-11e6-a3c3-37a522e81ab8","command_timeout":"600"}      [2016-07-13T01:23:36.187Z] INFO  [19057] : Command processor should execute command.      [2016-07-13T01:23:36.187Z] DEBUG [19057] : Storing current stage..      [2016-07-13T01:23:36.187Z] DEBUG [19057] : Stage_num does not exist. Not saving null stage. Returning..      [2016-07-13T01:23:36.187Z] DEBUG [19057] : Reading config file: /etc/elasticbeanstalk/.aws-eb-stack.properties      [2016-07-13T01:23:36.187Z] DEBUG [19057] : Retrieving metadata for key: AWS::ElasticBeanstalk::Ext||_ContainerConfigFileContent||commands..      [2016-07-13T01:23:36.188Z] DEBUG [19057] : Retrieving metadata for key: AWS::ElasticBeanstalk::Ext||_API||_Commands..      [2016-07-13T01:23:36.188Z] INFO  [19057] : Found enabled addons: ["logpublish"].      [2016-07-13T01:23:36.189Z] INFO  [19057] : Updating Command definition of addon logpublish.      [2016-07-13T01:23:36.189Z] DEBUG [19057] : Loaded definition of Command CMD-TailLogs.      [2016-07-13T01:23:36.189Z] INFO  [19057] : Executing CMD-TailLogs      [2016-07-13T01:23:36.190Z] INFO  [19057] : Executing command: CMD-TailLogs...      [2016-07-13T01:23:36.190Z] INFO  [19057] : Executing command CMD-TailLogs activities...      [2016-07-13T01:23:36.190Z] DEBUG [19057] : Setting environment variables..      [2016-07-13T01:23:36.190Z] INFO  [19057] : Running AddonsBefore for command CMD-TailLogs...      [2016-07-13T01:23:36.190Z] DEBUG [19057] : Running stages of Command CMD-TailLogs from stage 0 to stage 0...      [2016-07-13T01:23:36.190Z] INFO  [19057] : Running stage 0 of command CMD-TailLogs...      [2016-07-13T01:23:36.190Z] DEBUG [19057] : Loaded 1 actions for stage 0.      [2016-07-13T01:23:36.190Z] INFO  [19057] : Running 1 of 1 actions: TailLogs...  

Cron rake does not work

Posted: 13 Jul 2016 07:16 AM PDT

I am using whenever gem to run a rake task. In the log file I create I get this message:

bundler: command not found: rake Install missing gem executables with bundle install

I added this line in the whatever scheduler in order to solve an error that bundle can not be found: set :bundle_command, "/home/ubuntu/.gem/ruby/1.9.3/bin/bundle exec"

This is the cron command:

* * * * * /bin/bash -l -c 'cd /home/ubuntu/www/gizmo && RAILS_ENV=production /home/ubuntu/.gem/ruby/1.9.3/bin/bundle exec rake update_dashboard:update_data --silent >> /home/ubuntu/www/gizmo/log/cron.log 2>&1'  

When I copy/paste in to the terminal the rake task works but when the cron tries to run it I get the error.

Can any body help me ?

This is me schedule.rb file:

set :output, "#{path}/log/cron.log"  set :bundle_command, "/home/ubuntu/.gem/ruby/1.9.3/bin/bundle exec"  every 1.minutes do    rake "update_dashboard:update_data"  end  

This is my gem environment:

RubyGems Environment:    - RUBYGEMS VERSION: 1.8.11    - RUBY VERSION: 1.9.3 (2011-10-30 patchlevel 0) [x86_64-linux]    - INSTALLATION DIRECTORY: /home/ubuntu/.gem/ruby/1.9.3    - RUBY EXECUTABLE: /usr/bin/ruby1.9.1    - EXECUTABLE DIRECTORY: /home/ubuntu/.gem/ruby/1.9.3/bin    - RUBYGEMS PLATFORMS:      - ruby      - x86_64-linux    - GEM PATHS:       - /home/ubuntu/.gem/ruby/1.9.3       - /home/ubuntu/.gem/ruby/1.9.1       - /var/lib/gems/1.9.1    - GEM CONFIGURATION:       - :update_sources => true       - :verbose => true       - :benchmark => false       - :backtrace => false       - :bulk_threshold => 1000    - REMOTE SOURCES:       - http://rubygems.org/  

This is my ruby version

ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-linux]  

which ruby:

/usr/bin/ruby  

This is my rails version:

Rails 3.2.8  

which rails:

/home/ubuntu/.gem/ruby/1.9.3/bin/rails  

This is my rake file:

require 'inifile'    namespace :update_dashboard do    desc "Update BlueRuby Dashboard Data"    task :update_data => :environment do  libpath = File.expand_path '../', __FILE__    Braccount.all.each{|a|  file_name = libpath+'/account_'+a.id.to_s+'_data.ini'  if !File.exist?(file_name)    ini_file = IniFile.new(:filename => file_name)    else    ini_file = IniFile.load(file_name)  end    [30,60,90].each{|d|    sc = "Unique Groups "+d.to_s    if !ini_file.has_section?(sc)       ini_file[sc] = {}    end      from_date= (Time.zone.now-(d-1).days).to_date    visitors = a.brvisitors.where("DATE(brvisitors.updated_at) >= ?",from_date)    ini_file[sc]["Total"]=visitors.count      visitors.where("is_robot = false").joins(:bruniquegroup)            .select("bruniquegroups.name AS a_name,COUNT(brvisitors.id) as a_count")            .group("a_name")            .each{|u|              ini_file[sc][u.a_name]=u.a_count            }      ini_file[sc]["Robots"]=visitors.where("is_robot = true").count  }    sc = "Counter"  if !ini_file.has_section?(sc)    ini_file[sc] = {}    ini_file[sc]["value"]=0  end  ini_file[sc]["value"]=ini_file[sc]["value"]+1    ini_file.save  }    end  end  

Trailblazer Reform: validation_groups crashing

Posted: 13 Jul 2016 07:15 AM PDT

I'm setting up a deployment of Trailblazer, however I'm a new Rails user and I could use a little direction about this problem.

I've installed all the required Gems, however the Reform gem, is not running properly and it's throwing an error.

 loading extension..."/Users/smilingbuddha/web/aardvark/app/concepts/recent_upgrade/contract"     Exiting    /Users/smilingbuddha/.rvm/gems/ruby-2.3.0/gems/reform-2.2.1/lib/reform/validation.rb:6:in `validation_groups': undefined local variable or method `validation_group_class' for RecentUpgrade::Contract::Create:Class (NameError)    Did you mean?  validation_groups          from /Users/smilingbuddha/.rvm/gems/ruby-2.3.0/gems/reform-2.2.1/lib/reform/validation.rb:13:in `validation'          from /Users/smilingbuddha/.rvm/gems/ruby-2.3.0/gems/reform-2.2.1/lib/reform/validation.rb:19:in `validates'           from /Users/smilingbuddha/web/aardvark/app/concepts/recent_upgrade/contract.rb:8:in `<class:Create>'          from /Users/smilingbuddha/web/aardvark/app/concepts/recent_upgrade/contract.rb:3:in `<module:Contract>'          from /Users/smilingbuddha/web/aardvark/app/concepts/recent_upgrade/contract.rb:1:in `<top (required)>'  

This is the error:

validation_groups: undefined local variable or method validation_group_class for RecentUpgrade::Contract::Create:Class (NameError)

Any ideas how I can get this application running? Thank you!

Here's a section of the validation code we are using in the application in contract.rb

 property :property_id   validates :property_id, presence: true  

Autocomplete UI query array issue

Posted: 13 Jul 2016 07:12 AM PDT

I am using mongoid, ruby 2.2.1, and Rails 4 and have a field that is an Array. I can't figure out the method to query only the array items that have the :term or user typed input in them. Here is my method but it does not work. Right now when I query EVERY item in the array shows up. So I know I need this method to show just the array items that contain the user input.

  def autocomplete      @trans_array = Transaction.order_by(trans_names: :desc).where("trans_names like %#{params[:term]}")      render json: @trans_array.map(&:trans_names)    end  

Advance search with elasticsearch and rails

Posted: 13 Jul 2016 07:04 AM PDT

I want to use ElasticSearch to search with multiple parameters (name, sex, age at a time).

what I've done so far is included elastic search in my model and added a as_indexed_json method for indexing and included relationship.

require 'elasticsearch/model'    class User < ActiveRecord::Base      include Elasticsearch::Model    include Elasticsearch::Model::Callbacks        belongs_to :product      belongs_to :item      validates :product_id, :item_id, :weight, presence: true    validates :product_id, uniqueness: {scope: [:item_id] }      def as_indexed_json(options = {})      self.as_json({        only: [:id],        include: {          product: { only: [:name, :price] },          item: { only: :name },        }      })    end    def self.search(query)      # i'm sure this method is wrong I just don't know how to call them from their respective id's      __elasticsearch__.search(        query: {          filtered: {            filter: {              bool: {                must: [                  {                    match: {                      "product.name" => query                      }                  }                ],                must: [                  {                    match: {                      "item.name" => query                    }                  }                ]              }            }          }        }      )    end    end    User.import force: true  

And In controller

def index  @category = Category.find(params[:category_id])  if params[:search].present? and params[:product_name].present?    @users = User.search(params[:product_name]).records  end  if params[:search].present? and params[:product_price].present?    @users = User.search(params[:product_price]).records  end  if params[:search].present? and params[:item].present?    if @users.present?      @users.search(item: params[:item], product: params[:product_name]).records    else      @users = User.search(params[:item]).records    end  end  

end

There are basically 3 inputs for searching with product name , product price and item name, This is what i'm trying to do like if in search field only product name is present then

@users = User.search(params[:product_name]).records  

this will give me records but If user inputs another filter say product price or item name in another search bar then it's not working. any ideas or where I'm doing wrong :/ stucked from last 3 days

Handling Rack Timeout exceptions

Posted: 13 Jul 2016 07:09 AM PDT

I am using the Rack-timeout gem and a Rack::Timeout::RequestTimeoutException occurs. I did no configuration outside of putting this gem into my gemfile.

How do I handle these exceptions so that they don't stop the normal app's procedure but instead just log and let me know about them?

How to get params for url with whitespace as '%20' instead of '+' in Rails

Posted: 13 Jul 2016 07:49 AM PDT

If I have this params for adding to the URL

params = { name: 'John Key' }

and use the method to_param:

params.to_param   => "name=John+Key"  

The point is that '+' is not correctly read by the service used and is needed '%20' instead name=John%20Key: When to encode space to plus (+) or %20?

Is there a way to return the params with '%20' without using gsub?

Extending `find_by` with custom keys

Posted: 13 Jul 2016 06:51 AM PDT

In ActiveRecord sometimes you have virtual attributes based on real attributes. I.E.

class User < ApplicationRecord    def full_name      [first_name, last_name].reject(&:blank?).join ' '    end      def full_name= new_val      self.last_name, self.first_name = *new_val.reverse.split(' ', 2).each(&:reverse!)    end  end  

Now lets say I want to support searching by full name. I can do something like:

class User < ApplicationRecord    def self.find_by_full_name name      where("first_name || ' ' || last_name = ?", name).first    end  end  

This works but the search method is using the older find_by_* style finder rather than the newer find_by attribute: value style. Is there a hook where I can extend the newer style rather than have to use the old style?

I.E. I want:

User.find_by full_name: 'John Doe'  

Rather than:

User.find_by_full_name 'John Doe'  

Rails 4 : Child object doesn't save -entirly- using nested form

Posted: 13 Jul 2016 07:56 AM PDT

I want to be able to create an Ice Cream object/s while creating an Order object using the same form, I have followed Rails casts tutorial on this subject, Viewed many other questions and answers, And nothing seems to work. I can create the Order and I manged to got the Ice Cream object to be saved Thanks to Pavan's answer BUT NOT ENTIRLY. Seems I've problems with my check boxes Flavors & Extras , Please help. Here's my code...

order.rb

class Order < ActiveRecord::Base      belongs_to :user      belongs_to :shift      has_many :ice_creams      accepts_nested_attributes_for :ice_creams  end  

ice_craem.rb

class IceCream < ActiveRecord::Base      belongs_to :size      belongs_to :basis      has_and_belongs_to_many :flavors      belongs_to :sauce      belongs_to :topping      has_many :added_extras      has_many :extras, :through => :added_extras      belongs_to :order  end  

orders_controller.rb

 class OrdersController < ApplicationController    before_action :set_order, only: [:show, :edit, :update, :destroy]      # GET /orders    # GET /orders.json    def index      @orders = Order.all    end      # GET /orders/1    # GET /orders/1.json    def show    end      # GET /orders/new    def new      @order = Order.new      @order.ice_creams.build      @ice_cream = IceCream.new    end      # GET /orders/1/edit    def edit    end      # POST /orders    # POST /orders.json    def create      @order = Order.new(order_params)        respond_to do |format|        if @order.save          format.html { redirect_to @order, notice: 'Order was successfully created.' }          format.json { render :show, status: :created, location: @order }        else          format.html { render :new }          format.json { render json: @order.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /orders/1    # PATCH/PUT /orders/1.json    def update      respond_to do |format|        if @order.update(order_params)          format.html { redirect_to @order, notice: 'Order was successfully updated.' }          format.json { render :show, status: :ok, location: @order }        else          format.html { render :edit }          format.json { render json: @order.errors, status: :unprocessable_entity }        end      end    end      # DELETE /orders/1    # DELETE /orders/1.json    def destroy      @order.destroy      respond_to do |format|        format.html { redirect_to orders_url, notice: 'Order was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_order        @order = Order.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def order_params        params.require(:order).permit(:shift_id, :user_id, :discount, :total, :total_after_discount, :paid, :remaining, ice_creams_attributes: [:size_id, :basis_id, :sauce_id, :topping_id, :extra_one_id, :extra_two_id, :extra_three_id, :extra_four_id, :extra_five_id, :ice_cream_price, :extras_price, :total_price, :flavor_ids => [], :extra_ids => []])      end  end  

New order form: _form.html.erb

<%= form_for(@order) do |f| %>    <% if @order.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@order.errors.count, "error") %> prohibited this order from being saved:</h2>          <ul>        <% @order.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>    <%= f.hidden_field :user_id, value: current_user.id %>    <%= f.hidden_field :shift_id, value: get_shift %>      <%= f.fields_for :ice_creams do |builder| %>      <div class="field">        <%= builder.label :size_id %><br>        <%= builder.collection_select :size_id, Size.all, :id, :name, {prompt: true}, {class: ""} %>      </div>      <div class="field">        <%= builder.label :basis_id %><br>        <%= builder.collection_select :basis_id, Basis.all, :id, :name, {prompt: true}, {class: ""} %>      </div>        <div class="">        <%= hidden_field_tag "ice_cream[flavor_ids][]", nil %>        <% Flavor.all.each do |flavor| %>          <%= check_box_tag "ice_cream[flavor_ids][]", flavor.id, @ice_cream.flavor_ids.include?(flavor.id), class: 'flvs' %>          <%= flavor.name %> <br>        <% end %>      </div>        <div class="field">        <%= builder.label :sauce_id %><br>        <%= builder.collection_select :sauce_id, Sauce.all,:id,:name, {prompt: true}, {class: ""} %>      </div>      <div class="field">        <%= builder.label :topping_id %><br>        <%= builder.collection_select :topping_id, Topping.all,:id,:name, {prompt: true}, {class: ""} %>      </div>        <div class="">        <%= hidden_field_tag "ice_cream[extra_ids][]", nil %>        <% Extra.all.each do |extra| %>          <%= check_box_tag "ice_cream[extra_ids][]", extra.id, @ice_cream.extra_ids.include?(extra.id) %>          <%= extra.name %> <br>        <% end %>      </div>        <div class="field">        <%= builder.label :ice_cream_price %><br>        <%= builder.text_field :ice_cream_price %>      </div>      <div class="field">        <%= builder.label :extras_price %><br>        <%= builder.text_field :extras_price %>      </div>      <div class="field">        <%= builder.label :total_price %><br>        <%= builder.text_field :total_price %>      </div>    <% end %>      <div class="field">      <%= f.label :discount %><br>      <%= f.number_field :discount %>    </div>    <div class="field">      <%= f.label :total %><br>      <%= f.text_field :total %>    </div>    <div class="field">      <%= f.label :total_after_discount %><br>      <%= f.text_field :total_after_discount %>    </div>    <div class="field">      <%= f.label :paid %><br>      <%= f.text_field :paid %>    </div>    <div class="field">      <%= f.label :remaining %><br>      <%= f.text_field :remaining %>    </div>    <div class="actions">      <%= f.submit %>    </div>  <% end %>  

Thank you

Cannot Load Such File - Active Support

Posted: 13 Jul 2016 06:32 AM PDT

I am trying to start a rails server, but I get the error:

/Users/<username>/RubyWorkspace/<appname>/vendor/bundle/gems/railties-5.0.0/lib/rails/commands/rake_proxy.rb:2:in `require': cannot load such file -- active_support (LoadError)  

When I go to /vendor/bundle and list the gems, I don't see active support:

actioncable-5.0.0       minitest-5.9.0  actionmailer-5.0.0      multi_json-1.12.1  actionpack-5.0.0        nio4r-1.2.1  actionview-5.0.0        pkg-config-1.1.7  activejob-5.0.0         rack-2.0.1  activemodel-5.0.0       rack-test-0.6.3  activerecord-5.0.0      rails-5.0.0  arel-7.0.0              rails-dom-testing-2.0.1  builder-3.2.2           rails-html-sanitizer-1.0.3  byebug-9.0.0            railties-5.0.0  byebug-9.0.5            rake-11.2.2  coffee-rails-4.2.1      rb-fsevent-0.9.7  coffee-script-2.4.1     rb-inotify-0.9.7  coffee-script-source-1.10.0 sass-3.4.22  concurrent-ruby-1.0.2       sass-rails-5.0.5  debug_inspector-0.0.2       spring-1.7.1  erubis-2.7.0            spring-1.7.2  execjs-2.7.0            spring-watcher-listen-2.0.0  ffi-1.9.14              sprockets-3.6.3  globalid-0.3.6          sprockets-rails-3.1.1  i18n-0.7.0              thor-0.19.1  jbuilder-2.4.1          thread_safe-0.3.5  jbuilder-2.5.0          tilt-2.0.5  jquery-rails-4.1.1      turbolinks-5.0.0  listen-3.0.8            turbolinks-source-5.0.0  loofah-2.0.3            tzinfo-1.2.2  mail-2.6.4              uglifier-3.0.0  method_source-0.8.2     web-console-3.1.1  mime-types-3.1          web-console-3.3.1  mime-types-data-3.2016.0521 websocket-driver-0.6.4  mini_portile2-2.1.0     websocket-extensions-0.1.2  

But when I run bundle update, bundler says that it is using active support:

Using rake 11.2.2  ....  Using activesupport 5.0.0  ....  Bundle updated!  Gems in the group production were not installed.  

One thing that I believe could be causing the error, but I'm not sure, is when I run gem env, under gem paths, it shows:

- GEM PATHS:   - /Users/<username>/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0   - /Users/<username>/.gem/ruby/2.3.0  

Do I need to fix the gem paths, do I need to reinstall active support in a different directory, or is it something else entirely?

After validation error in create controller method cannot render new controller method

Posted: 13 Jul 2016 07:21 AM PDT

I have model validation as below on Ad model :

class Question < ActiveRecord::Base      validate :required_four_options   private    def required_four_options     if question_able_type == "Ad"      errors.add(:base, "Every question must have exact four option") if options.size != 4    end  end  end  

This is sending validation error in create controller method , i want to render new controller method if any validation error occurred. Following are my controller methods.

class AdsController < ApplicationController    def new        @campaign_id = params["campaign_id"] unless params["campaign_id"].nil?      @ad = Ad.new      @questions = @ad.questions.build      #4.times {@questions.options.build}      @questions.options.build    end    def create        @ad = Ad.new(ad_params)   respond_to do |format|          if @ad.save              format.html { redirect_to @ad, notice: 'Ad was successfully created.' }              format.json { render :show, status: :created, location: @ad }          else                format.html { render :action => :new }              format.json { render json: @ad.errors, status: :unprocessable_entity }          end      end  end  end  

As you can see if ad not saved i am rendering new action but it rendered index method dont know why , help me with this i dont know what i m doing wrong.

Rails4 where with conditions syntax

Posted: 13 Jul 2016 06:23 AM PDT

I'm trying to switch my app from rails 3.2 to 4.2.

q = User.find_all_by_attr(attr_value, :order => "name DESC", limit => 8).map { ... }  

Since find_all_by_ is deprecated I've changed it to

q = User.where(:attr => attr_value, :order => "name desc", limit => 8).map { ... }  

but now I am getting error that column name order doesn't exist.

What is a proper way to write this query in rails 4.2?

Same goes for User.find(:all). I've seen that using all is deprecated and am unable to find proper way.

Rails and href in haml

Posted: 13 Jul 2016 06:36 AM PDT

I am attempting to follow along with a tutorial for creating an Evernote-clone but running into trouble with this section on line 5 that is supposed to link back to a document. When I attempt to run it it gives me a TypeError in Docs#index and 'no implicit conversion of Doc into Integer':

.wrapper_with_padding      #docs.clearfix          -unless @docs.blank?              - @docs.each do |doc|                  %a{href: (url_for[doc])}                      .doc                          %p.title= link_to doc.title                          %p.date= time_ago_in_words(doc.created_at)                          %p.content= truncate(doc.content, length:50)          -else              %h2 Create Doc!              %p Start Creating Documents and Organizing Your Life!              %button= link_to "Create Doc", new_doc_path  

"Missing FROM-clause entry" when using nested merges with ActiveRecord

Posted: 13 Jul 2016 07:17 AM PDT

I'm trying to use ActiveRecord queries to select devices belonging to specific users in my DB (devices are just models containing push notifications keys), regarding how many orders users made, or other things.

(In all models I removed non relevant or private stuff)

Here is my Device model:

class Device < ActiveRecord::Base      belongs_to :user  end  

User model:

class User < ActiveRecord::Base    has_many :order    has_one :device  end  

Order model:

class Order < ActiveRecord::Base    belongs_to :user    belongs_to :order_status    scope :valid, -> { joins(:order_status).merge(OrderStatus.valid) }  end  

OrderStatus model:

class OrderStatus < ActiveRecord::Base    has_many :orders    scope :valid, -> { where.not(name: "processing") }  end  

So, with all these, i'm trying to get Devices belongings to users who have made more than x valid orders. Here is where i am:

Device.all.joins(:user).merge(User.joins(:order).merge(Order.valid).group("users.id").having("count(orders.id) > ?", [NB_ORDERS]))  

This generates this request:

: SELECT "devices".* FROM "devices" INNER JOIN "users" ON "users"."id"  = "devices"."user_id" LEFT OUTER JOIN "order_statuses" ON "order_statuses"."id" = "orders"."order_status_id" LEFT OUTER JOIN "orders" ON "orders"."user_id" = "users"."id" WHERE ("order_statuses"."name" != $1) GROUP BY users.id HAVING count(orders.id) > 10  

And gives me this error:

Hirb Error: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "orders" LINE 1: ... JOIN "order_statuses" ON "order_statuses"."id" = "orders"."...

What i really don't understand is that when i just do

User.joins(:order).merge(Order.valid).group("users.id").having("count(orders.id) > ?", [NB_ORDERS])  

It gives me the right result. It seems like nesting merges messes up with Postgres.

is there a way to solve this problem ? (I have a great amount of records so using SQL/ActiveRecord is essential)

RailsAdmin not working with Pundit - Pundit::AuthorizationNotPerformedError at / RailsAdmin::MainController

Posted: 13 Jul 2016 07:52 AM PDT

I'm using Devise and Pundit gems in a Ruby on Rails application. I'm trying to implement RailsAdmin in order to set up a simple admin interface for my non-tech team members, on the URL 'myapp.com/admin', but going to this URL raises the following error :

Pundit::AuthorizationNotPerformedError at / RailsAdmin::MainController

This error is raised by the file lib/pundit.rb in the following method:

def verify_authorized      raise AuthorizationNotPerformedError, self.class unless pundit_policy_authorized?    end

I understand this is linked to Pundit's policies but cannot find my way through the changes to perform.

Here is what I've tried until now :

In my Gemfile, I have installed :

gem "rails_admin"

and

gem "rails_admin_pundit", :github => "sudosu/rails_admin_pundit"

Then, in my terminal, I ran

'bundle'

In my initializers, I have :

RailsAdmin.config do |config|    ## == Devise ==    config.authenticate_with do      warden.authenticate! scope: :user    end    config.current_user_method(&:current_user)      ## == Pundit ==    config.authorize_with :pundit  end

In my controllers/application_controller.rb, I have the following code :

class ApplicationController < ActionController::Base    # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.    protect_from_forgery with: :exception      before_action :configure_permitted_parameters, if: :devise_controller?    before_action :authenticate_user!    include Pundit      after_action :verify_authorized, except: :index, unless: :devise_controller?    after_action :verify_policy_scoped, only: :index, unless: :devise_controller?      rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized      def user_not_authorized      flash[:alert] = "You are not authorized to perform this action."      redirect_to(root_path)    end      def default_url_options      { host: ENV['HOST'] || 'localhost:3000' }    end        private      def configure_permitted_parameters      devise_parameter_sanitizer.for(:sign_up) << [:first_name, :last_name, :bio, :email, :password, :password_confirmation, :photo, :photo_cache]      devise_parameter_sanitizer.for(:account_update) << [:first_name, :last_name, :bio, :email, :password, :password_confirmation, :photo, :photo_cache]    end    end

Last, in my policies/application_policy.rb (see at the end the 'def rails_admin?' method), I have :

class ApplicationPolicy    attr_reader :user, :record      def initialize(user, record)      @user = user      @record = record    end      def index?      false    end      def show?      scope.where(:id => record.id).exists?    end      def create?      false    end      def new?      create?    end      def update?      false    end      def edit?      update?    end      def destroy?      false    end      def scope      Pundit.policy_scope!(user, record.class)    end      class Scope      attr_reader :user, :scope        def initialize(user, scope)        @user = user        @scope = scope      end        def resolve        scope      end    end      def rails_admin?(action)      case action        when :dashboard          user.admin?        when :index          user.admin?        when :show          user.admin?        when :new          user.admin?        when :edit          user.admin?        when :destroy          user.admin?        when :export          user.admin?        when :history          user.admin?        when :show_in_app          user.admin?        else          raise ::Pundit::NotDefinedError, "unable to find policy #{action} for #{record}."      end    end  end

Would you have any idea about what I am missing? Thanks guys.

Encountered "SyntaxError in AssignmentsController#show" error when trying to use if else statement to check if a record exists in the database

Posted: 13 Jul 2016 07:46 AM PDT

I'm trying to use an if else statement in show.html.erb in the Assignment to check if a record in Bid exists. But I encountered a syntax error "SyntaxError in AssignmentsController#show" that occurs on the first line of the code below:

<%= if Bid.exists?(user_id: current_user.id, assignment_id: @assignment.id) %>    <p>it exists</p>  <%= else %>    <p>it doesn't exists</p>  

The following is the entire file Assignment/show.html.erb:

<p id="notice"><%= notice %></p>    <p>    <strong>Assignment:</strong>    <%= @assignment.assignment %>  </p>    <p>    <strong>Education:</strong>    <%= @assignment.education.education %>  </p>    <p>    <strong>Subject:</strong>    <%= @assignment.subject.subject %>  </p>    <p>    <strong>Gender prefer:</strong>    <%= @assignment.gender_prefer %>  </p>    <p>    <strong>Timeslot:</strong>    <%= @assignment.timeslot %>  </p>    <p>    <strong>Duration:</strong>    <%= @assignment.duration %>  </p>    <p>    <strong>Budget:</strong>    <%= @assignment.budget %>  </p>    <p>    <strong>Budget unit:</strong>    <%= @assignment.budget_unit %>  </p>    <p>    <strong>Assignment info:</strong>    <%= @assignment.assignment_info %>  </p>    <p>    <strong>Assignment id:</strong>    <%= @assignment.id %>  </p>    <%= if Bid.exists?(user_id: current_user.id, assignment_id: @assignment.id) %>    <p>it exists</p>  <%= else %>    <p>it doesn't exists</p>  <%= end %>    <%= link_to "Create Bid", bids_path(:status => "Pending", :assignment_id => @assignment.id, :user_id => current_user.id), :method => :post %> |  <%= link_to 'Bid', {controller: "bids", action: "new", id: @assignment.id} %> |  <%= link_to 'Bid', bid_path, method: :post %> |  <%= link_to 'Bid', edit_bid_path %> |  <%= link_to 'Edit', edit_assignment_path(@assignment) %> |  <%= link_to 'Back', assignments_path %>  

The following is the entire file assignments_controller.rb:

class AssignmentsController < ApplicationController    before_action :authenticate_user!    before_action :set_assignment, only: [:show, :edit, :update, :destroy]      # GET /assignments    # GET /assignments.json    def index      @assignments = Assignment.all    end      # GET /assignments/1    # GET /assignments/1.json    def show    end      # GET /assignments/new    def new      @assignment = Assignment.new    end      # GET /assignments/1/edit    def edit    end      # POST /assignments    # POST /assignments.json    def create      @assignment = Assignment.new(assignment_params)        respond_to do |format|        if @assignment.save          format.html { redirect_to @assignment, notice: 'Assignment was successfully created.' }          format.json { render :show, status: :created, location: @assignment }        else          format.html { render :new }          format.json { render json: @assignment.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /assignments/1    # PATCH/PUT /assignments/1.json    def update      respond_to do |format|        if @assignment.update(assignment_params)          format.html { redirect_to @assignment, notice: 'Assignment was successfully updated.' }          format.json { render :show, status: :ok, location: @assignment }        else          format.html { render :edit }          format.json { render json: @assignment.errors, status: :unprocessable_entity }        end      end    end      # DELETE /assignments/1    # DELETE /assignments/1.json    def destroy      @assignment.destroy      respond_to do |format|        format.html { redirect_to assignments_url, notice: 'Assignment was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_assignment        @assignment = Assignment.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def assignment_params        params.require(:assignment).permit(:assignment, :education_id, :subject_id, :gender_prefer, :timeslot, :duration, :budget, :budget_unit, :assignment_info)      end  end  

I've tried simple if else statements which stills returns an error:

<%= if 1 > 0 %>    <p>it exists</p>  <%= else %>    <p>it doesn't exists</p>  <%= end %>  

Uncaught ReferenceError: RailsAdmin is not defined

Posted: 13 Jul 2016 05:33 AM PDT

My RailsAdmin is working good but such things like progress bars, multi checkboxes and dropdown lists are not working. Moreover, this problem is seen only in production mode. At my localhost it's fine. At production I have these errors in my browser's console:

Uncaught TypeError: Cannot read property 'push' of undefined

Uncaught ReferenceError: RailsAdmin is not defined

How can I make javascript to execute in RailsAdmin panel in production mode?

Rails 4 Bootsrap Modal

Posted: 13 Jul 2016 06:33 AM PDT

This is a shopping cart to sell vitamins and supplements. I have a shelf model serving as a placeholder to display products. The products are grouped by Serving groups "30 servings, 60 servings etc..."

Using a link, I'm trying to open a modal with the supplement facts picture of the product.

I'm trying to pass the id of the product in the link like this:

<%= link_to " Supplement Facts", "#pictureModal", "data-toggle" => "modal", :id => @product %>  

Also tried this:

<%= link_to " Supplement Facts", "#pictureModal", "data-toggle" => "modal", :product_id => @product %>  

The problem is that the picture opening in the modal belongs to the Shelf and not the product. I'm guessing that the product id is not being passed to the modal. To confirm that this is happening I've included this line in the modal to check the product id, but instead I'm getting the shelf id:

<%= @product.id  if @product.present? %>  

Is this a better approach?: How to add bootstrap modal with link_to so the link content open in modal ? I also followed the answer in that question without success.

Thanks!

routes.rb

Myapp::Application.routes.draw do      resources :servings    resources :brands    resources :categories    resources :charges    resources :shipping_addresses, only: [:update, :create, :edit, :destroy, :new, :index]    resources :subproducts      get 'order_items/create'      get 'order_items/update'      get 'order_items/destroy'      get 'check_shipping_address' => 'orders#check_shipping_address'      get 'my_account' => 'users#my_account'      resources :orders    resources :purchases, only: [:show, :destroy, :update]      # get 'orders/checkout' => 'orders/#checkout'      resources :products, only: [:show, :destroy, :update]    resources :shelves, only: [:show, :destroy, :update]    resource :cart, only: [:show]    resources :order_items, only: [:create, :update, :destroy]      get "admin" => "admin#index"    get "admin_products" => "admin#admin_products"    get "admin_edit_shelf" => "admin#edit_shelf"      scope '/admin' do      resources :products, only: [:create, :edit, :destroy, :new, :index]      resources :shelves, only: [:create, :edit, :destroy, :new, :index]      resources :attachments      resources :users      resources :zip_code_validations    end        resources :locations    scope do     get "locations_landing" => "locations#landing"     get "locations_invalid" => "locations#invalid"    end      get "user_location" => "locations#user_location"        devise_for :users, :controllers => {:registrations => 'registrations'}      # devise_for :users, controllers: { sessions: "users/sessions" }            root to: 'landing#hsnow_index'        get "commerce/store"      get "search_products" => "commerce#search_products"       get "search_shelves" => "commerce#search_shelves"    end  

Serving.rb

class Serving < ActiveRecord::Base      has_many :products      belongs_to :shelf  end  

Shelf.rb

class Shelf < ActiveRecord::Base    belongs_to :brand    has_many :attachments, dependent: :destroy    has_many :products    has_many :servings, dependent: :destroy    has_and_belongs_to_many :categories    belongs_to :category    has_attached_file :main_image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/product/factss/no-image-available"    validates_attachment :main_image, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }        has_attached_file :facts, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/product/factss/no-image-available"    validates_attachment :facts, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }     #array of picture attachments          def attachments_array=(array)         array.each do |file|             attachments.build(:attachment => file)         end      end    # Search for shelves by name              def self.search_by_shelf_name(search)          where("LOWER(name) LIKE ?", "%#{search.downcase}%")       end    end  

Product.rb

class Product < ActiveRecord::Base    has_many :order_items    has_many :attachments, dependent: :destroy    has_many :subproducts    has_and_belongs_to_many :categories    belongs_to :brand    belongs_to :shelf    belongs_to :serving    has_attached_file :main_image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/product/factss/no-image-available"    validates_attachment :main_image, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }        has_attached_file :facts, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/product/factss/no-image-available"    validates_attachment :facts, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }          default_scope { where(active: true) }    #array of picture attachments        def attachments_array=(array)         array.each do |file|             attachments.build(:attachment => file)         end      end   # Search for products by name          def self.search_by_product_name(search)          where("LOWER(name) LIKE ?", "%#{search.downcase}%")       end    end  

Shelves Controller

  def show      @order_item = current_order.order_items.new        @serving = Serving.new      @product = Product.find(params[:id])          @shelf = Shelf.find(params[:id])      @servings = @shelf.servings     end  

shelves/show.html.erb

<!-- Serving groups and Products in servings -->  <!-- ################################ -->  <!-- ################################ -->            <% if @shelf.multiproduct? %>                  <% @shelf.servings.each do |serving| %>              <div class="row">                   <div class="col-xs-8 col-md-4 text-navy">                      <h3><%= serving.serving_size %></h3>                  </div>                   <div class="col-xs-4 col-md-4 text-right">                      <h3><strong><%= serving.price %></strong></h3>                  </div>                                  </div>              <div class="row">                  <div class="col-md-12">                  <% if current_user.role_id == 1 %>                      <%= link_to "edit", edit_serving_path(serving) %> |                      <%= link_to "delete", serving, method: :delete, data: { confirm: 'Are you sure?' } %>                  <% end %>                  </div>                                          </div>              <div class="row">                   <div class="col-xs-12 col-md-8 text-left">                      <%= pluralize serving.products.count,'Flavor' %>                       <hr style="margin-top: 5px;">                     </div>              </div>          <% serving.products.each do |product| %>              <div class="row">                  <div class="col-xs-12 col-md-8">                   <div class="col-xs-6 col-md-4" style="<%= "padding-top: 0.6em;" if product.flavor.split.size <= 2 %> >"                      <p><strong><%= product.flavor %></strong></p>                   </div>                    <div class="col-xs-2 col-md-4 " style="<%= "padding-top: 0.6em;" if product.flavor.split.size <= 2 %> >" >    <!-- Link to open modal with supplement facts picture-->  <!-- ################################ -->                        <i class="fa fa-file-image-o" aria-hidden="true"></i> <%= link_to " Supplement Facts", "#pictureModal", "data-toggle" => "modal", :id => @product, class:""  %>    <!-- ################################ -->                  </div>                     <div class="col-xs-4 col-md-4 text-right">                      <%= form_for @order_item, remote: true do |f| %>                          <%= f.hidden_field :quantity, value: 1, class: "form-control", min: 1 %>                          <%= f.hidden_field :product_id, value: product.id %>                          <%= f.submit "ADD", class: "btn btn-secondary" %>                      <% end %>                          </div>                  </div>              </div>              <div class="row">                  <div class="col-md-12">                  <% if current_user.role_id == 1 %>                      <%= link_to "edit", edit_product_path(product) %> |                      <%= link_to "delete", product, method: :delete, data: { confirm: 'Are you sure?' } %>                  <% end %>                  </div>                                          </div>              <br>          <% end %> <!-- end product block -->                  <hr></hr>              <% end %>   <!-- end servings block -->           <% end %> <!-- end conditional checking if shelf multi product is false -->        <!-- PRODUCT FACTS MODAL  -->  <!-- ################################ -->  <!-- ################################ -->    <div class="modal inmodal" id="pictureModal" tabindex="-1" role="dialog" aria-hidden="true">      <div class="modal-dialog">          <div class="modal-content animated bounceInRight">              <div class="modal-header">                  <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>              </div>              <div class="modal-body">                  <div class="row">                      <div class="col-xs-12">                          <%= image_tag @product.facts.url if @product.present? %>                          <%= @product.id  if @product.present? %>                      </div>                  </div>                </div>              <div class="modal-footer">                  <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>              </div>          </div>      </div>  </div>  

Use an integer & string to rails date/time helper

Posted: 13 Jul 2016 05:33 AM PDT

I have two values saved in my database that I would like to use as a Date helper in Rails.

For example, num is an Integer value of 2 and period is a String a value of days. Id like to use them as follows:

2.days.from_now   

I've tried the following with no success:

num.period.from_now  

How can I achieve this?

Any help much appreciated.

Ruby on Rails - While I am trying to run test throws an error with a database view?

Posted: 13 Jul 2016 05:25 AM PDT

I am trying to start writing tests for an application. The technology stack is Ruby 2.3.1, Rails 5.0.0, Postgres 9.5

When I execute this line of code

$ rails test test/controllers/static_pages_controller_test.rb  

I get this error

# Running:    E    Error:  StaticPagesControllerTest#test_should_get_home:  ActiveRecord::StatementInvalid: PG::ObjectNotInPrerequisiteState: ERROR:  cannot delete from view "consultants_clients_tasks"  DETAIL:  Views that do not select from a single table or view are not automatically updatable.  HINT:  To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule.  : DELETE FROM "consultants_clients_tasks"      Error:  StaticPagesControllerTest#test_should_get_home:  NoMethodError: undefined method `each' for nil:NilClass  

Here is the code of the test

require 'test_helper'    class StaticPagesControllerTest < ActionDispatch::IntegrationTest      def setup      @base_title = "Company"    end      test "should get home" do      get root_url      assert_response :success      assert_select :title, "Home | #{@base_title}"    end    end  

The database view indeed is a result from multiple inner joins from different tables, but I do not understand what the hint is telling me to do.

Pagination on the same partial with different variables passed (will_paginate)

Posted: 13 Jul 2016 05:10 AM PDT

How do I use pagination on the same partial with different variables passed?

I have a library show page in my Rails app that has a list of books:

libraries_controller.rb:

def show     @books = @library.books.paginate(page: params[:books_page], per_page: 10)  end  

libraries/show.haml:

#books_table    = render "books_list", books: @books  

libraries/show.js.erb:

$('#books_table').replaceWith('<%= j render "books_list", books: @books %>');  

A 'books_list' partial has a pagination link which works fine:

books/_books_list.haml:

...  = paginate books, param_name: 'books_page'  

When I add a new book to the list, #books_table is automatically replaced with _books partial like so (books/create.js.erb):

$('#books_table').replaceWith('<%= j render "libraries/books_list", books: @library_books%>')  

books_controller.rb:

def create    @library_book = @library.books.create(book_params)    @library_books = @library.books.paginate(page: params[:books_page], per_page: 10)  end  

But at this point pagination doesn't work. Any ideas how should I proceed?

1 comment:

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

    ReplyDelete