Sunday, June 12, 2016

Rails absolute time from reference + french "ago" string | Fixed issues

Rails absolute time from reference + french "ago" string | Fixed issues


Rails absolute time from reference + french "ago" string

Posted: 12 Jun 2016 06:56 AM PDT

I need to reimport some data that was exported using the "ago" stringification helper, in French.

I have a reference Time/DateTime date at which the import was done, and from there I need to substract this "time ago" difference to find the absolute time.

Eg

IMPORT_DATE = Time.parse('Sat, 11 Jun 2016 15:15:19 CEST +02:00')  parse_relative_time(from: IMPORT_DATE, ago: 'Il y a 5j') # 'Il y a 5j" = "5d ago"  # => Should output sthing like Sat, 6 Jun 2016 (DateTime object)  parse_relative_time(from: IMPORT_DATE, ago: 'Il y a 1 mois') # 'Il y a 5j" = "1 month ago"  # => 11 May 2016 (it's not big deal if it's 10 or 11 or 12 because of months with odd numbers, just need something approximate)  

Slow activerecord/postgres query not utilizing index

Posted: 12 Jun 2016 07:01 AM PDT

I have a Messages table with user_id field (string). A query for total unique users is extremely slow with over a million records.

Message.where(created_at: start_date..end_date).select(:user_id).distinct(:user_id).count  => (120145.6ms)  SELECT DISTINCT COUNT(DISTINCT "messages"."user_id") FROM "messages" WHERE ("messages"."created_at" BETWEEN '2016-05-14 04:00:00.000000' AND '2016-06-13 03:59:59.999000')  

I have indexes on user_id & created_at, but postgres doesn't seem to use them:

Schema

add_index "messages", ["user_id"], name: "index_messages_on_user_id", using: :btree  add_index "messages", ["created_at"], name: "index_messages_on_created_at", using: :btree     

PG Explain

                                                                        QUERY PLAN  -----------------------------------------------------------------------------------------------------------------------------------------------------------------   HashAggregate  (cost=56111.04..56291.89 rows=18085 width=29)     Group Key: user_id     ->  Seq Scan on messages  (cost=0.00..52215.65 rows=1558153 width=29)           Filter: ((created_at >= '2016-05-14 04:00:00'::timestamp without time zone) AND (created_at <= '2016-06-13 03:59:59.999'::timestamp without time zone))  (4 rows)  

Why are the indexes not used? Any tips for speeding up the query?

deploy with capistrano issue

Posted: 12 Jun 2016 06:47 AM PDT

I'm trying to deploy with capistrano.

I can ssh into my server and the the server ssh key is added to my bitbucket profile.

I get the following error: Does anybody knows what the problem could be?

01 bundle exec rake assets:precompile    01 DEPRECATION WARNING: The configuration option `config.serve_static_assets` has been renamed to `config.serve_static_files` to clarify its role (it merely enables…    01    01 DEPRECATION WARNING: You did not specify a `log_level` in `production.rb`. Currently, the default value for `log_level` is `:info` for the production environment…    01    01    config.log_level = :info    01    01 . (called from block in tsort_each at /home/deploy/.rbenv/versions/2.2.3/lib/ruby/2.2.0/tsort.rb:226)    01    01 rake aborted!    01 NameError: uninitialized constant Mailboxer    01 /opt/www/03truxx/releases/20160612124038/config/initializers/mailboxer.rb:1:in `<top (required)>'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/engine.rb:652:in `block in load_config_initializer'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.2/lib/active_support/notifications.rb:166:in `instrument'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/engine.rb:651:in `load_config_initializer'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/engine.rb:615:in `each'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/engine.rb:615:in `block in <class:Engine>'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:30:in `instance_exec'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:30:in `run'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:55:in `block in run_initializers'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:44:in `each'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:44:in `tsort_each_child'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:54:in `run_initializers'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/application.rb:352:in `initialize!'    01 /opt/www/03truxx/releases/20160612124038/config/environment.rb:5:in `<top (required)>'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/application.rb:328:in `require'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/application.rb:328:in `require_environment!'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/application.rb:457:in `block in run_tasks_blocks'    01 /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/sprockets-rails-3.0.4/lib/sprockets/rails/task.rb:62:in `block (2 levels) in define'    01 /home/deploy/.rbenv/versions/2.2.3/bin/bundle:23:in `load'    01 /home/deploy/.rbenv/versions/2.2.3/bin/bundle:23:in `<main>'    01 Tasks: TOP => environment    01 (See full trace by running task with --trace)  

and then

(Backtrace restricted to imported tasks)  cap aborted!      ** DEPLOY FAILED  ** Refer to log/capistrano.log for details. Here are the last 20 lines:  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/engine.rb:651:in `load_config_initializer'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/engine.rb:615:in `each'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/engine.rb:615:in `block in <class:Engine>'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:30:in `instance_exec'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:30:in `run'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:55:in `block in run_initializers'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:44:in `each'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:44:in `tsort_each_child'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/initializable.rb:54:in `run_initializers'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/application.rb:352:in `initialize!'  /opt/www/03truxx/releases/20160612124038/config/environment.rb:5:in `<top (required)>'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/application.rb:328:in `require'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/application.rb:328:in `require_environment!'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/railties-4.2.2/lib/rails/application.rb:457:in `block in run_tasks_blocks'  /opt/www/03truxx/shared/bundle/ruby/2.2.0/gems/sprockets-rails-3.0.4/lib/sprockets/rails/task.rb:62:in `block (2 levels) in define'  /home/deploy/.rbenv/versions/2.2.3/bin/bundle:23:in `load'  /home/deploy/.rbenv/versions/2.2.3/bin/bundle:23:in `<main>'   DEBUG [ba9c6e96]   Tasks: TOP => environment   DEBUG [ba9c6e96]   (See full trace by running task with --trace)  

gem file:

source 'https://rubygems.org'  ruby '2.2.3'  gem 'rails', '4.2.2'  gem 'bcrypt', '3.1.7'  gem 'faker', '1.4.2'  gem 'carrierwave', '0.10.0'  gem 'mini_magick', '3.8.0'  #gem 'fog', '1.26.0'  gem 'will_paginate', '3.0.7'  gem 'bootstrap-will_paginate', '0.0.10'  gem 'bootstrap-sass', '3.2.0.0'  gem 'sass-rails', '5.0.2'  gem 'uglifier', '2.5.3'  gem 'coffee-rails', '4.1.0'  gem 'jquery-rails', '4.0.3'  gem 'turbolinks', '2.3.0'  gem 'jbuilder', '2.2.3'  gem 'sdoc', '0.4.0', group: :doc    group :development, :test do  gem 'sqlite3', '1.3.9'  #gem 'byebug', '3.4.0'  gem 'web-console', '2.0.0.beta3'  gem 'spring', '1.1.3'  gem 'rake', '11.1.2'  gem 'mailboxer'        end  group :test do  gem 'minitest-reporters', '1.0.5'  gem 'mini_backtrace', '0.1.3'  gem 'guard-minitest', '2.3.1'  end  group :production do  gem 'pg', '0.17.1'  gem 'rails_12factor', '0.0.2'  gem 'puma', '2.11.1'  end    group :development do    #gem 'better_errors'    gem 'unicorn'    gem 'pry-rails'    gem 'pry-nav'    gem 'meta_request'    gem 'capistrano', '~> 3.4.1'      gem 'capistrano-bundler', '~> 1.1.2'    gem 'capistrano-rails', '~> 1.1.1'    gem 'capistrano-ssh-doctor', '~> 1.0'    gem 'net-ssh', '~> 2.0'    # Add this if you're using rbenv    #gem 'capistrano-rbenv', github: "capistrano/rbenv"  end  

config/application.rb

require File.expand_path('../boot', __FILE__)    require 'rails/all'    # Require the gems listed in Gemfile, including any gems  # you've limited to :test, :development, or :production.  Bundler.require(*Rails.groups)    module SampleApp2    class Application < Rails::Application      # Settings in config/environments/* take precedence over those specified here.      # Application configuration should go into files in config/initializers      # -- all .rb files in that directory are automatically loaded.        # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.      # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.      # config.time_zone = 'Central Time (US & Canada)'        # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.      # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]      # config.i18n.default_locale = :de        # Do not swallow errors in after_commit/after_rollback callbacks.      config.active_record.raise_in_transactional_callbacks = true    end  end  

config/initializers/mailboxer.rb

Mailboxer.setup do |config|      #Configures if you application uses or not email sending for Notifications and Messages    config.uses_emails = true      #Configures the default from for emails sent for Messages and Notifications    config.default_from = "no-reply@mailboxer.com"      #Configures the methods needed by mailboxer    config.email_method = :mailboxer_email    config.name_method = :name      #Configures if you use or not a search engine and which one you are using    #Supported engines: [:solr,:sphinx]    config.search_enabled = false    config.search_engine = :solr      #Configures maximum length of the message subject and body    config.subject_max_length = 255    config.body_max_length = 32000  end  

config/deploy.rb

# config valid only for current version of Capistrano  lock '3.5.0'    set :application, '03truxx'  set :repo_url, 'git@bitbucket.org:r2artene/03trux.git'  set :deploy_to, '/opt/www/03truxx'  set :user, 'deploy'  set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets}    # Default branch is :master  # ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp    # Default deploy_to directory is /var/www/my_app_name  # set :deploy_to, '/var/www/my_app_name'    # Default value for :scm is :git  # set :scm, :git    # Default value for :format is :pretty  # set :format, :pretty    # Default value for :log_level is :debug  # set :log_level, :debug    # Default value for :pty is false  # set :pty, true    # Default value for :linked_files is []  # set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/secrets.yml')    # Default value for linked_dirs is []  # set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system')    # Default value for default_env is {}  # set :default_env, { path: "/opt/ruby/bin:$PATH" }    # Default value for keep_releases is 5  # set :keep_releases, 5    namespace :deploy do      %w[start stop restart].each do |command|      desc 'Manage Unicorn'      task command do        on roles(:app), in: :sequence, wait: 1 do          execute "/etc/init.d/unicorn_#{fetch(:application)} #{command}"        end            end    end      after :publishing, :restart    after :restart, :clear_cache do    on roles(:web), in: :groups, limit: 3, wait: 10 do        end    end  end  

How to debug grape api

Posted: 12 Jun 2016 05:33 AM PDT

module Employee      class Data < Grape::API          resource :employee_data do               desc "Description of all employees"              get do                   EmpDatum.all              end                desc "create a new employee"                  params do                       requires :name, type: String                      requires :address, type: String                      requires :age, type: Integer                  end                  post  do                      EmpDatum.create!({                 name: params[:name],                 address: params[:address],                 age: params[:age]                            })                  end              end      end  end  

Get request is working fine. However when sent a POST request,

curl http://localhost:3000/api/v1/employee_data.json -d "name='jay';address='delhi';age=25"

{"error":"address is missing, age is missing"}%        

I am unable to put byebug in the above post block. I am unable to see the params that are getting passed. What am I missing here

Rails 3 + Carrierwave + jQuery File Upload fails to upload image file to Openshift server

Posted: 12 Jun 2016 06:00 AM PDT

I am trying to upload image file of size 3.7 MB to Openshift server and get all the time 503 Service Temporarily Unavailable error:

Service Temporarily Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. Apache/2.2.15 (Red Hat) Server at webauto-webauto.rhcloud.com Port 80

When I upload images of smaller size everything works well. Please give me some advise how I can solve this problem?

Rails default model translation files for my language

Posted: 12 Jun 2016 05:20 AM PDT

Where can I find the translation files used by Rails to translate model-related interpolated strings for my language ?

The Rails documentation has some information there, but this is all blabla and what I really want is the default file used by Rails that outputs the default messages I can see.

And I'm not talking about model/attributes translation, I also already do that, but what I want is to be able to copy the fr.yml file that contains all the structure for messages.

For example the translation

My email cannot be blank  Mon email doit être rempli(e) # fr translation  

Where can I find the (LATEST) files that define

"%{attribute} cannot be blank"  "%{attribute} doit être rempli(e)"  

So that I can redefine them to (for example)

"You have to fill %{attribute}"  "Vous devez remplir le champ %{attribute}"  

I don't even understand where those translations are/where to look at them. I18n ? ActiveModel ? ActiveSupport ? ActiveRecord/Mongoid ?

I really want to copy the whole file, because I need to make sure no untranslated strings go through.

I am using Rails 5 and Mongoid Edge.

BONUS : I'd also like to generate some sample translations based on what my models look like, is there some kind of framework/script that crawls the models, and print an example of every string that can appear given the validations in place, etc. ?

How to solve n+1 query issue with includes - Rails

Posted: 12 Jun 2016 05:39 AM PDT

I'm using the bullet gem to find out what n+1 query problems my app has, and it turns out I have 3 issues:

user: Rashed N+1 Query detected Sale => [:shop] Add to your finder: :includes => [:shop] user: Rashed N+1 Query detected Shop => [:malls] Add to your finder: :includes => [:malls] user: Rashed N+1 Query detected Shop => [:categories] Add to your finder: :includes => [:categories]

The problem is i'm not really sure how to go about solving the problem using includes because of how my models are associated with eachother. I have 4 models, Sale, Shop, Mall, and Category. These are the associations for my models:

class Shop < ActiveRecord::Base      has_many :categorizations      has_many :categories, :through => :categorizations      has_many :mall_shops      has_many :malls, :through => :mall_shops      has_many :sales, dependent: :destroy  end    class Sale < ActiveRecord::Base      belongs_to :shop  end    class Mall < ActiveRecord::Base      has_many :mall_shops      has_many :shops, :through => :mall_shops      has_many :sales, :through => :shops  end    class Category < ActiveRecord::Base      has_many :categorizations      has_many :shops, :through => :categorizations      has_many :sales, :through => :shops  end  

In my Sale index page, im displaying all the Sales records, and each sale record belongs to a shop, and each shop has many categories and many malls. For every Sale record displayed im iterating through all the malls and categories that that Sale's Shop belong to (for filtering purposes). This is the relevant code in my Sale index page:

 <% @sales.each do |sale| %>    <div class="<% sale.shop.malls.each do |m| %> mall<%= m.id %><% end %><% sale.shop.categories.each do |c| %> category<%= c.id %><% end %>">    .  .    end  

And my Sale's Controller:

class SalesController < ApplicationController   def index      @malls = Mall.all.order('name ASC')      @categories = Category.all.order('category_type ASC')      @shops = Shop.all      @sales = Sale.where('offer_end >= ?', Date.today).order('offer_end ASC')    end  end  

So what would be the best way to solve the n+1 query issue I have? to get a better idea of my app this is the website im building: www.shopwatchkw.com

Rails String in View with whitespaces

Posted: 12 Jun 2016 05:39 AM PDT

I'm trying to show a string with xml content (correct with whitespaces etc.) in a rails view.

My Controller action read a xml file and put this content into a string. For example

  @xml_content = "       <main>        <children>           <a>           </a>           <b>           </b>        </children>      </main>      "  

Then I get this string from my controller and want to show this xml content in a view.

<%= @xml_content %>  

But when I print this string in the view all whitespaces get lost and I get something like this:

     <main><children><a></a><b></b></children></main>  

Printing the same string in the console with "puts @xml_content" create the correct output.

What can I do to show this xml content with all whitespaces in the view?

EDIT: Controller:

@file = File.open(@xml_device_description.get_file_path)    @xml_content = Nokogiri::XML @file   

I need to create two objects in same form (rails)

Posted: 12 Jun 2016 04:52 AM PDT

so please imagine a form for a car reservation, the form contains both some client information(name, age, city..) and also the reservation informations(start_date, end_date...). So obviously, i need to create in the same form a client first, based on the informations and then the reservation which is related to the created client:

class Client < ActiveRecord::Base    has_many :reservations  end      

.

class Reservation < ActiveRecord::Base    belongs_to :client    belongs_to :voiture  end  

Here is what i did until now(bad way). The reservation informations start with f.text_field, and the client informations only with text_field(very bad way yes :( )

<%= form_for([@voiture, @voiture.reservations.new]) do |f| %>    <div class="row">      <div class="col-md-12 price_tag">          <span><%= @voiture.price %>Dhs</span>          <span class="pull-right">Par jour</span>      </div>  </div>    <div class="row">      <div class="col-md-6">          <label>Nom</label>          <%= text_field :nom, readonly: 'true', placeholder: 'Nom', class: 'form-control' %>           </div>      <div class="col-md-6">          <label>Prenom</label>          <%= text_field :prenom, readonly: 'true', placeholder: 'Prenom', class: 'form-control', disabled: 'true' %>           </div>  </div>    <div class="row">      <div class="col-md-6">          <label>CIN</label>          <%= text_field :cin, readonly: 'true', placeholder: 'CIN', class: 'form-control' %>           </div>      <div class="col-md-6">          <label>Age</label>          <%= text_field :age, readonly: 'true', placeholder: 'Age', class: 'form-control', disabled: 'true' %>             </div>  </div>    <div class="row">      <div class="col-md-6">          <label>Ville</label>          <%= text_field :ville, readonly: 'true', placeholder: 'Ville', class: 'form-control' %>           </div>      <div class="col-md-6">          <label>Télephone</label>          <%= text_field :telephone, readonly: 'true', placeholder: 'Telephone', class: 'form-control', disabled: 'true' %>             </div>  </div>    <div class="row">      <div class="col-md-6">          <label>Email</label>          <%= text_field :email, readonly: 'true', placeholder: 'Email', class: 'form-control' %>           </div>  </div>    <div class="row">      <div class="col-md-6">          <label>Check In</label>          <%= f.text_field :start_date, readonly: 'true', placeholder: 'Start Date', class: 'form-control' %>           </div>      <div class="col-md-6">          <label>Check Out</label>          <%= f.text_field :end_date, readonly: 'true', placeholder: 'End Date', class: 'form-control', disabled: 'true' %>             </div>  </div>    <%= f.hidden_field :voiture_id, value: @voiture.id %>  <%= f.hidden_field :prix, value: @voiture.prix %>  <%= f.hidden_field :total, id: 'reservation_total' %>  <%= f.submit "Book Now", id:"btn_book", class: "btn btn-primary wide", disabled: 'true' %>   

Controller :

class ReservationsController < ApplicationController    before_action :authenticate_user!      def create      @client = Client.create(client_params)      @reservation = @client.reservations.create(reservation_params)        redirect_to @reservation.voiture, notice: "Votre reservation a bien ete cree"    end      def reservation_params      params.require(:reservation).permit(:start_date, :end_date, :prix, :total, :voiture_id)    end      def client_params      params.permit(:nom, :prenom, :cin, :age, :ville, :telephone, :email)    end  end  

I'm sure there is a good and clean way to do that.. Thanks !

Rails deploy to subdomain x or y depending on environment variables

Posted: 12 Jun 2016 04:01 AM PDT

I have a Rails website mounted on an autoscaling AWS EC2 group, with Passenger/Apache. The deployment is done using Capistrano, I am getting the list of all the servers and deploying to each of them from a bastion host.

I need to be able to switch the subdomain I want to release to using environment variables, eg I should be able to deploy either to www.mysite.com or prod.mysite.com, by simply setting an environment variable.

This is done on the Rails/Capistrano side. I am using capistrano_env to pull the deploy host and do something like env.add 'HOST', deploy_host

The problem is about URLs redirections. My apache file specifies the valid hosts as serverName + alias (www, prod), however ideally, the client would be redirected to only www or prod depending on which site he has typed in his browser.

Here is my current vHost file on port 80 (port 443 is fine)

<VirtualHost *:80>          ServerName "www.example.com"          ServerAlias "production.example.com"          DocumentRoot "/var/www/mysite/current/public/"          Redirect "/" "https://production.example.com/"  </VirtualHost>  

The most important problem that needs to be tackled here:

Redirect "/" "https://production.example.com/"

The redirection should be done to either https://www or https://prod depending on the URL typed in the client's browser (if the user types http://www, he will currently be redirected to https://prod which is bad)

I was wondering how to best tackle the problem

  • Using mod_rewrite ? I've heard bad things about that...
  • Rails app redirection ? Basically if the app was deployed to www, then environment HOST variable will contain https://www.example.com so maybe we can intercept every request and redirect if the request host is different from the Rails routing side.

What do you think ? I am not using deployment solutions like Chef for lack of time/existing code, but I am definitely considering to switch to something like that when there's time. In the meantime I need to find not-so-dirty hacks, that still lets me deploy with one command.

AngularJS routing with Rails

Posted: 12 Jun 2016 03:55 AM PDT

I begin to use AngularJS with my Rails application but when i tried to implement my route providers with Angular, it's not working and Rails view is displayed instead of my template.

routes.rb :

root 'tutorials#index'  

TutorialsController :

    def index      @tutorials = Tutorial.all        respond_to do |format|          format.html          format.json { render :json => @tutorials }      end  end  

app/views/tutorials/index.html.erb :

<html ng-app="Tutorial">  <body>      <div class="container" ng-view>      </div>  </body>  

assets/javascripts/tutorials.js :

var Tutorial = angular.module('Tutorial', ['ngRoute']);  

Tutorial.config(function($routeProvider, $locationProvider){

$log.debug( "Configuring $routeProvider...");

$locationProvider.html5Mode(true);    $routeProvider.  when('/tutorials', {      templateUrl: '../templates/tutorials/index.html',      controller: 'TutorialController'  }).  otherwise({      templateUrl: '../templates/tutorials/index.html',      controller: 'TutorialController'  });  

});

and assets/templates/tutorials/index.html just displayed tutorials' title with a controller not shown in tutorials.js because it's not relevant here.

So instead having my angular route provider redirect me to index.html, i have a blank page representing my index.html.erb.

Any idea ?

Thanks!

multiple nested forms within a ruby on rails project

Posted: 12 Jun 2016 03:53 AM PDT

I am trying to use multiple nested attributes within a form, though only the first set of attributes appears to be appearing.

Below is the HAML template

.mdl-cell.mdl-cell--10-col.mdl-cell--1-offset    %h3.mdl-typography--display-1= t('.account_title')    = form.fields_for :address do |address_fields|      .mdl-grid        .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--6-col          = address_fields.text_field :first_name, class: 'mdl-textfield__input'          = address_fields.label :first_name, class: 'mdl-textfield__label'        .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--6-col          = address_fields.text_field :last_name, class: 'mdl-textfield__input'          = address_fields.label :last_name, class: 'mdl-textfield__label'        .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--6-col          = form.text_field :name, class: 'mdl-textfield__input'          = form.label :name, class: 'mdl-textfield__label'        .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--6-col          = form.email_field :email, class: 'mdl-textfield__input'          = form.label :email, class: 'mdl-textfield__label'    %h3.mdl-typography--display-1= t('.bank_title')    = form.fields_for :account do |account_fields|      .mdl-grid        .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--6-col          = account_fields.text_field :bsb, class: 'mdl-textfield__input'          = account_fields.label :bsb, class: 'mdl-textfield__label'        .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--6-col          = account_fields.text_field :account_number, class: 'mdl-textfield__input'          = account_fields.label :account_number, class: 'mdl-textfield__label'        .mdl-textfield.mdl-js-textfield.mdl-textfield--floating-label.mdl-cell.mdl-cell--12-col          = account_fields.text_field :account_name, class: 'mdl-textfield__input'          = account_fields.label :account_name, class: 'mdl-textfield__label'  

Definitions in Model

accepts_nested_attributes_for :address, reject_if: proc { |attributes| attributes['address1'].blank? }    accepts_nested_attributes_for :trading_hours    accepts_nested_attributes_for :phones, :reject_if => lambda { |t| ( t['display_number'].gsub(/\D+/, '').blank?) }    accepts_nested_attributes_for :account  

Rails deploy on aws using puma, capistrano and nginx error - webpage not available

Posted: 12 Jun 2016 03:26 AM PDT

Hi i have a rails app trying to deploy on aws instance

These are my configurations

config/deploy.rb

lock '3.5.0'    set :application, 'fullpower_tee'  set :repo_url, 'git_repo_url' # Edit this to match your repository  set :branch, :master  set :deploy_to, '/home/deploy2/fullpower_tee'  set :pty, true  set :linked_files, %w{config/database.yml config/application.yml}  set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads}  set :keep_releases, 5  set :rvm_type, :user  set :rvm_ruby_version, 'ruby-2.2.1'      set :puma_rackup, -> { File.join(current_path, 'config.ru') }  set :puma_state, "#{shared_path}/tmp/pids/puma.state"  set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"  set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock"    #accept array for multi-bind  set :puma_conf, "#{shared_path}/puma.rb"  set :puma_access_log, "#{shared_path}/log/puma_error.log"  set :puma_error_log, "#{shared_path}/log/puma_access.log"  set :puma_role, :app  set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))  set :puma_threads, [0, 8]  set :puma_workers, 0  set :puma_worker_timeout, nil  set :puma_init_active_record, true  set :puma_preload_app, false  

Gemfile

gem 'figaro'  gem 'puma'  group :development do    gem 'capistrano'    gem 'capistrano3-puma'    gem 'capistrano-rails', require: false    gem 'capistrano-bundler', require: false    gem 'capistrano-rvm'  end  

Capfile

# Load DSL and set up stages  require "capistrano/setup"    # Include default deployment tasks  require "capistrano/deploy"    require 'capistrano/bundler'  require 'capistrano/rvm'  require 'capistrano/rails/assets' # for asset handling add  require 'capistrano/rails/migrations' # for running migrations  require 'capistrano/puma'    Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }  

environments/production.rb

Hadean::Application.configure do    # Rails 4    config.eager_load = true    config.assets.js_compressor = :uglifier      # Settings specified here will take precedence over those in config/environment.rb      config.force_ssl = true      # The production environment is meant for finished, "live" apps.    # Code is not reloaded between requests    config.cache_classes = true      # Compress JavaScripts and CSS    config.assets.compress = true      # Don't fallback to assets pipeline if a precompiled asset is missed    config.assets.compile = false      # Generate digests for assets URLs    config.assets.digest = true      # config.assets.precompile += %w( *.css *.js )      # Add the fonts path    config.assets.paths << "#{Rails.root}/app/assets/fonts"      # Precompile additional assets    config.assets.precompile += %w( .svg .eot .woff .ttf )    config.assets.precompile += %w( *.js )    config.assets.precompile += [ 'admin.css',                                  'admin/app.css',                                  'admin/cart.css',                                  'admin/foundation.css',                                  'admin/normalize.css',                                  'admin/help.css',                                  'admin/ie.css',                                  'autocomplete.css',                                  'application.css',                                  'chosen.css',                                  'foundation.css',                                  'foundation_and_overrides.css',                                  'home_page.css',                                  'ie.css',                                  'ie6.css',                                  'login.css',                                  'markdown.css',                                  'myaccount.css',                                  'normalize.css',                                  'pikachoose_product.css',                                  'product_page.css',                                  'products_page.css',                                  'shopping_cart_page.css',                                  'signup.css',                                  'site/app.css',                                  'sprite.css',                                  'tables.css',                                  'cupertino/jquery-ui-1.8.12.custom.css',# in vendor                                  'modstyles.css', # in vendor                                  'scaffold.css' # in vendor                                  ]      # Full error reports are disabled and caching is turned on    config.consider_all_requests_local       = false    config.action_controller.perform_caching = true      # if ENV['FOG_DIRECTORY'].present?    #   config.action_controller.asset_host = "//#{ENV['FOG_DIRECTORY']}.s3.amazonaws.com"    # end      # Specifies the header that your server uses for sending files    config.action_dispatch.x_sendfile_header = "X-Sendfile"      # For nginx:    # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'      # If you have no front-end server that supports something like X-Sendfile,    # just comment this out and Rails will serve the files    config.cache_store = :memory_store    #config.cache_store = :dalli_store      # See everything in the log (default is :info)    # config.log_level = :debug      # Use a different logger for distributed setups    # config.logger = SyslogLogger.new      # Use a different cache store in production    # config.cache_store = :mem_cache_store      # Disable Rails's static asset server    # In production, Apache or nginx will already do this    config.serve_static_files = true    config.paperclip_defaults = {        :storage => :s3,        :s3_credentials => {            :bucket => 'fullpowertee',            :access_key_id => 'AWS_KEY',            :secret_access_key => 'AWS_SECRET'        },        :s3_region => 'Oregon'    }    # Enable serving of images, stylesheets, and javascripts from an asset server    # config.action_controller.asset_host = "http://assets.example.com"      config.action_mailer.default_url_options = { :host => 'ror-e.herokuapp.com' }    # Disable delivery errors, bad email addresses will be ignored    # config.action_mailer.raise_delivery_errors = false      # Enable threaded mode    # config.threadsafe!      # Enable locale fallbacks for I18n (makes lookups for any locale fall back to    # the I18n.default_locale when a translation can not be found)    config.i18n.fallbacks = true      # Send deprecation notices to registered listeners    config.active_support.deprecation = :notify    end  

On the AWS Instance server I have

/etc/nginx/sites-available/default

upstream app {    # Path to Puma SOCK file, as defined previously    server unix:/home/deploy2/fullpower_tee/shared/tmp/sockets/puma.sock fail_timeout=0;  }    server {    listen 80;    server_name localhost;      root /home/deploy2/fullpower_tee/current/public;      try_files $uri/index.html $uri @app;      location / {      proxy_set_header X-Forwarded-Proto $scheme;      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header X-Real-IP $remote_addr;      proxy_set_header Host $host;      proxy_redirect off;      proxy_http_version 1.1;      proxy_set_header Connection '';      proxy_pass http://app;    }      location ~ ^/(assets|fonts|system)/|favicon.ico|robots.txt {      gzip_static on;      expires max;      add_header Cache-Control public;    }      error_page 500 502 503 504 /500.html;    client_max_body_size 4G;    keepalive_timeout 10;  }  

I am able to successfully deploy using the capistrano and i get the success message from the capistrano that the server is up and running

and also i can see from

/home/deploy2/fullpower_tee/shared/log/puma_error.log

* Inherited unix:///home/deploy2/fullpower_tee/shared/tmp/sockets/puma.sock  * Restarting...  Refreshing Gemfile  Puma starting in single mode...  * Version 3.4.0 (ruby 2.2.1-p85), codename: Owl Bowl Brawl  * Min threads: 0, max threads: 8  * Environment: production  * Daemonizing...  === puma startup: 2016-06-12 08:44:07 +0000 ===  

Also i have already done the sudo service nginx restart after the deployment

now everything seems to be fine but when i try to hit the public ip of the AWS Instance it stucks on loading and the browser throws the error

This webpage is not available    ERR_CONNECTION_TIMED_OUT  

Please Help me out i am stuck into this issue since a day

Bootstrap flash alert CSS not working correctly in mobile screen

Posted: 12 Jun 2016 04:22 AM PDT

I am currently building a Rails app. In my app, I show flash message using Bootstrap's CSS on alert. I am not fully using Bootstrap's CSS but adding only related to alert in my app due to overlap in CSS.

CSS for flash works fine for normal desktop screen. It's position is centered and fixed. Image below:

enter image description here

However, when I populate the flash on mobile screen (lesser than 500px), then it is off-centered to left no matter what I do. Image below: enter image description here

I am confused why this is happening. Just like the descktop screen, I would like to fix the position of flash in mobile screen and always populate on a same place.

Following is the view code I have for the flash

<div id="flash-message-wrapper">      <% flash.each do |type, message| %>          <div class="alert <%= alert_class_for(type) %> alert-dismissible fade in">              <button type="button" class="close" data-dismiss="alert">                  <span aria-hidden="true">&times;</span>                  <span class="sr-only">Close</span>              </button>              <%= message %>       <% end %>  </div>  

The CSS for this code is :

.alert {    padding: 15px;    margin-bottom: 20px;    border: 1px solid transparent;    border-radius: 4px;  }  .alert h4 {    margin-top: 0;    color: inherit;  }  .alert .alert-link {    font-weight: bold;  }  .alert > p,  .alert > ul {    margin-bottom: 0;  }  .alert > p + p {    margin-top: 5px;  }  .alert-dismissable,  .alert-dismissible {    padding-right: 35px;  }    .alert-dismissable .close,  .alert-dismissible .close {    position: relative;    top: -2px;    right: -21px;    color: inherit;  }  .alert-success {    color: #3c763d;    background-color: #dff0d8;    border-color: #d6e9c6;  }  .alert-success hr {    border-top-color: #c9e2b3;  }  .alert-success .alert-link {    color: #2b542c;  }  .alert-info {    color: #31708f;    background-color: #d9edf7;    border-color: #bce8f1;  }  .alert-info hr {    border-top-color: #a6e1ec;  }  .alert-info .alert-link {    color: #245269;  }  .alert-warning {    color: #8a6d3b;    background-color: #fcf8e3;    border-color: #faebcc;  }  .alert-warning hr {    border-top-color: #f7e1b5;  }  .alert-warning .alert-link {    color: #66512c;  }  .alert-danger {    color: #a94442;    background-color: #f2dede;    border-color: #ebccd1;  }  .alert-danger hr {    border-top-color: #e4b9c0;  }  .alert-danger .alert-link {    color: #843534;  }    .fade {    opacity: 0;    -webkit-transition: opacity .15s linear;         -o-transition: opacity .15s linear;            transition: opacity .15s linear;  }  .fade.in {    opacity: 1;  }    .close {    float: right;    font-size: 21px;    font-weight: bold;    line-height: 1;    color: #000;    text-shadow: 0 1px 0 #fff;    filter: alpha(opacity=20);    opacity: .2;  }  .close:hover,  .close:focus {    color: #000;    text-decoration: none;    cursor: pointer;    filter: alpha(opacity=50);    opacity: .5;  }  button.close {    -webkit-appearance: none;    padding: 0;    cursor: pointer;    background: transparent;    border: 0;  }    .sr-only {    position: absolute;    width: 1px;    height: 1px;    padding: 0;    margin: -1px;    overflow: hidden;    clip: rect(0, 0, 0, 0);    border: 0;  }  .sr-only-focusable:active,  .sr-only-focusable:focus {    position: static;    width: auto;    height: auto;    margin: 0;    overflow: visible;    clip: auto;  }    #flash-message-wrapper {      position: fixed;      top: 50px;          left: 50%;          margin-left: -250px;      width: 600px;  }    @media (max-width: 500px) {      #flash-message-wrapper {          position: fixed;          top: 50px;              right: 50%;              margin-right: -250px;          width: 300px;      }  }  

Any help would be appreciated!

Rspec and Draper : unitialized constant on class name

Posted: 12 Jun 2016 03:16 AM PDT

On Rails 4 when I execute rspec tests for a decorator I got the following error :

/app/spec/decorators/my_decorator_spec.rb:3:in `<top (required)>': uninitialized constant MyDecorator (NameError)  

I'm surely missing something but I don't know what.

I generate the decorator

rails g decorator My  

A spec/my_decorator_spec.rb file is generated, with the content :

require 'spec_helper'    describe MyDecorator do  end  

Then I test

rspec spec/decorators/my_decorator_spec.rb  

I didn't add anything in application.rb or spec_helper.rb. The decorator itself works correctly.

EDIT

It's weirder than I expected. When I test all rspec files, tests inside my decorator spec file are correctly executed.

It works :

rspec spec/  

It doesn't :

rspec spec/decorators  rspec spec/decorators/my_decorator_spec.rb  

Run group of test in rspec

Posted: 12 Jun 2016 06:22 AM PDT

My application has some functions that are using httparty service to get data from another website. So it takes a lot of time when run the test for http functions.

- spec  -- services  --- http_request  ---- test_http_a_spec.rb  ---- test_http_b_spec.rb  --- component  ---- test_component_c_spec.rb  ---- test_component_d_spec.rb  --- models  ---- test_model_e_spec.rb  

So how can I run rspec test for all tests except the tests in http_request folder ? Thanks

Rails routes have no id

Posted: 12 Jun 2016 02:32 AM PDT

I added resource :products, :path => 'catalog/' to my routes.rb, but my routs look like this:

      products POST   /catalog(.:format)                            products#create    new_products GET    /catalog/new(.:format)                        products#new   edit_products GET    /catalog/edit(.:format)                       products#edit                 GET    /catalog(.:format)                            products#show                 PATCH  /catalog(.:format)                            products#update                 PUT    /catalog(.:format)                            products#update                 DELETE /catalog(.:format)                            products#destroy  

Why do they have no :ids? For example, product#show should have URI /products/:id(.:format), right?

Also, = link_to products_path(product), class: 'product' do leads me to http://localhost:3000/catalog.1

Missing params when save to postgres table column

Posted: 12 Jun 2016 04:54 AM PDT

All was well before changing my db schema

Before:

...  t.string :skills, :string  ...  

After:

...    t.string :skills, array: true, default: '{}'  end    add_index :table_name, :skills, using: 'gin'  ...  

In log console I can see the params as:

"project"=>{"skills"=>"Wordpress,OpenCart,Magneto","Spree Commerce"}  

This part I can't understand what's going on (still in console log):

SQL (0.8ms)  INSERT INTO "projects"... ["skills", "{ordpress,\"OpenCart\",Magneto}"]  

Why the "W", in Wordpress is chopped off? Where is "Spree Commerce"?

Do I need to add something else on the index column?

My controller has the standard permit :skills and nothing in model project.rb

undefined local variable or method `env' for main:Object

Posted: 12 Jun 2016 01:40 AM PDT

this is a ruby on rails project for recipe finder

i am getting this error
NameError in RecipesController#index
undefined local variable or method `env' for main:Object

recipe.rb

class Recipe < ActiveRecord::Base    include HTTParty      key_value = ENV['FOOD2FORK_KEY']    hostport = ENV['FOOD2FORK_SERVER_AND_PORT'] || 'www.food2fork.com'    base_uri "http://#{hostport}/api/search"    default_params key: key_value    format :json      def self.for term      get("", query: { query: term})['recipes']    end  end  

recipes_controller.rb

class RecipesController < ApplicationController    def index      @search_term = params[:search] ||  'chocolate'      @recipes = Recipe.for(@search_term)    end  end  

recipes_controller.rb

class RecipesController < ApplicationController    def index      @search_term = params[:search] ||  'chocolate'      @recipes = Recipe.for(@search_term)    end  end  

i am using rails 4.2.6 and ruby 2.2.0

When should we use vendor/assets/images and when just assets/images?

Posted: 12 Jun 2016 01:30 AM PDT

I haven't found any documentation as to when, why or what images should we use in vendor, and which ones in assets/images.

All I see referenced is third-party scripts and stylesheets, but not images.

Can you please explain why?

How to restrict credit card number displaying as plain text?

Posted: 12 Jun 2016 02:21 AM PDT

In my project I am working with activemerchant gem where when I give credit card number it is stored as "xxxx-xxx-xxx-1111". Here there is an issue. While we try to submit / input the details, in the log my credit card number is displayed (ex: 1111-1111-1212-1111) as plain text but while storing in database it is fine.

While entering itself I want to see number in the log as "xxxx-xxxx-xxxx-1111". How it can be possible? Please help.

Masonry Leaving Whitespaces/Gaps

Posted: 12 Jun 2016 02:10 AM PDT

Working with masonry.js, it is being populated by rails but is leaving gaps all over the place, I tried two layouts and the pictures and corresponding codes are below.How may I get rid of the gaps indicated by the red arrows.Research states that it may not pack all the way and I should use packery however I've seen examples of masonry filling entire websites like here Example

Layout 1 enter image description here

Layout 1 code

HTML

<div id="restaurants">          <%@restaurant.each do |f| %>              <div class="box">                <%= image_tag f.thumbnail.url(:medium)%>            </div>          <% end %>    </div>  

Javascript

$(window).load(function(){     $('#restaurants').masonry({          itemSelector: '.box',         gutter: 0,         columnWidth: 1            });  });  

CSS

.box {    height: 320px;    width: 320px;    margin: 0;  }  

Layout 2 (which I prefer more)

enter image description here

All the code remains the same except the css which is just

.box {     margin: 0;  }  

Rails could not find gem

Posted: 12 Jun 2016 04:21 AM PDT

when tried to start server rails s i have got

 Could not find minitest-5.9.0 in any of the sources      Run `bundle install` to install missing gems.  

i did gem install minitest -v 5.9.0

Successfully installed minitest-5.9.0

1 gem installed

also gem list

minitest (5.9.0, 4.7.5)  

but when i try rails s again i received the same error.

How could i fix it?

Is there a way to put multiple parameters in routing parameters?

Posted: 12 Jun 2016 02:10 AM PDT

I have a route get '/catalog/:gender/' => 'catalog#gender'. The :gender param is used in my controller like so @products = Product.where(gender: params[:gender]).all.

So I can use /catalog/male/ to get all male products and /catalog/female/ to get all female products. The question is, is there a way somebody could possibly pass both male and female parameters and get all the products?

no method error when saving to database fails

Posted: 12 Jun 2016 02:38 AM PDT

So I'm having people submit a question using a form, then I display all the questions on the same page. It works fine when the validation passes (minimum 25 characters) but when it doesn't pass, I get this error:

NoMethodError in Questions#create  Showing /home/ubuntu/workspace/app/views/static_pages/home.html.erb where line #20 raised:    undefined method `each' for nil:NilClass  Extracted source (around line #20):    <div class="row">      <div class="col-md-12">          <% @questions.each do |question| %> <--- this is line 20          <p> <%= question.content %></p>          <% end %>          </div>  

I don't really know what's going on. Any ideas?

app/controllers/static_pages_controller:

class StaticPagesController < ApplicationController    def home      @questions= Question.all    end      def help    end  end  

views/static_pages/home

<div class="row">      <div class="col-md-12">          <% @questions.each do |question| %>          <p> <%= question.content %></p>          <% end %>          </div>    </div>  

app/controllers/questions_controller:

class QuestionsController < ApplicationController  #before_action :logged_in_user, only: [:create]      def create      @question = Question.new(question_params) #this might not work      if @question.save      flash[:success] = "Question added"      redirect_to root_path      else        flash[:danger] = "Add question failed. Try making the question longer."        render 'static_pages/home'      end      end        private      def question_params    params.require(:question).permit(:content)    end    end  

models/question.rb

class Question < ActiveRecord::Base      validates :content, presence: true, length: { minimum: 25}  end  

Using Javascript properly in Rails

Posted: 12 Jun 2016 01:15 AM PDT

So I have some .js file in app/assets/javascripts and in my home.html.erb file I want to use wheel.js to populate a particular canvas with what the javascript does.

The below is what I have so far.

<!DOCTYPE html>  <html lang="en">      <body>          <div class="centered">              <canvas id="drawing_canvas"></canvas>              <div id="status_label">loading...</div>          </div>          <script src="assets/javascripts/p2.min.js"></script>          <script src="assets/javascripts/wheel.js"></script>  

...

In the src, I've tried app/assets/javascripts/p2.min.js, assets/p2.min.js, leading with / and not leading with /

However, all of them do not work. In console, I see Error: GET [domain]/assets/javascripts/p2.min.js or whatever way I try to load in the javascript (same for the other script following)

And looking at resources, from developer tools, I see that those resources somehow don't exist.

I've tried reading Rails tutorials and stuff, but I can't seem to find a solution

(as for JS being broken, I've tested the JS with just a regular HTML page and it spawned it correctly. Copying that HTML page into the erb somehow creates problems)

Rails nested form with select2

Posted: 12 Jun 2016 01:54 AM PDT

I use cocoon gem for the nested forms and use select2 for the custom selects.

The first collection select has worked as expected. When I add another select item even though the select items have the same class, it hasn't worked. I tried this solution. But it hasn't solved to my problem. Because I have called as a partial to nested items.

_form.html

 <%= simple_form_for(@course) do |f| %>     <%= f.simple_fields_for :course_teachers do |course_teacher| %>       <%= render "course_teacher_fields", :f => course_teacher %>     <% end %>     <div class="links">       <%= link_to_add_association 'Add Teacher', f, :course_teachers, class:"btn btn-info" %>     </div>   <%end%>  

_course_teacher_fields.html

<div class="nested-fields">    <%= f.association :teacher, collection: Teacher.all, label_method: :full_name_with_title, input_html: {class: "teacher"} %><br/>  </div>  

app.js

$(".teacher").select2({    placeholder: "Select Teacher",    allowClear: true  });  

Do you have any idea?

Shopify API - How can i update product order on Smart Collection with thousands of products?

Posted: 12 Jun 2016 12:33 AM PDT

I am using Shopify's Ruby Gem to organize Smart Collections in a product store. Essentially I am trying to do a nightly update to the product order on these collections (their sort order is set to manual). The goal is to sort products based on sales data, but also put out of stock items at the end of the list.

I managed to write a script that works well on most collections:

@scs = ShopifyAPI::SmartCollection.find(:all,params: {limit: 250})  @scs.each do |sc|          sc.order(products: @products_in_order)          sc.save  end  

Unfortunately if the collection is larger than a couple hundred products, the URI becomes too long and I get this error:

ActiveResource::ClientError: Failed. Response code = 414. Response message = Request-URI Too Large.

Is there any way to update product order on large smart collections in an efficient way? Some of my collections have upwards of 1000 products, and I do not want to have to update each "collect" individually as I will be running this script on a daily basis.

Any advice is appreciated.

Rails Devise: Should I use current_user or stick to User.find(params[:user_id])

Posted: 12 Jun 2016 12:48 AM PDT

I wanted to know when using Devise for my User model is there any difference in using @user = current_user.id vs @user = User.find(params[:user_id]) in my controllers and views(only current_user). What would be considered the "better" way.

Example:

  def index      current_user    end  

or

  def index      @user = User.find(current_user.id)    end  

or

 def index     @user = User.find(params[:user_id])   end  

Querying a rails db column

Posted: 12 Jun 2016 02:31 AM PDT

I'm looking for a similar way to query the database like this but struggling how to go about what I want.

I'm not just looking for the answer, I also seek where do you find the methods to use. I have searched for postgres db query, rails db query but nothing shows up that matches what I want, or even close.

foo = "a,b,c,d"  b.bar #=> "b,d,a,f,z" Code shorten for the B Class.    B.where('bar like ?', "%#{foo}")  

I know that returns nothing. I want if any of foo's value is included in b.bar column, then return it.

If foo = "a", I would get a result but foo can have more than one values.

Im using Ruby 2.2.5. Rails 5. DB: PostgreSQL

Will upgrade to Ruby 2.3 if code is much simple.

No comments:

Post a Comment