Sunday, July 17, 2016

Rails more than one skip_before_action | Fixed issues

Rails more than one skip_before_action | Fixed issues


Rails more than one skip_before_action

Posted: 17 Jul 2016 07:51 AM PDT

I want to do more than one skip_bevore_action

tried this:

  skip_before_action :user_logged_in, :user_is_provider, only: [:impressum, :agb, :help, :privacy]  

but the

:user_is_provider

function isn't called yet. The function is in application_controller.rb

Thanks

Getting associated model attributes using strings

Posted: 17 Jul 2016 07:45 AM PDT

I am building a custom method and i want to access attributes by using strings.

for example

@search["attribute_name"]  

While this works, when i try to get associated attribute values its not working.

example: @search["category_id"]["name"]

can someone point me in the right direction here?

Proper use of polymorphic association for reports

Posted: 17 Jul 2016 07:42 AM PDT

I have a Category model that has_many Link and Text posts, and those posts have many Reports.

How should I best set up my models/schema to retrieve all reports for the category by using @category.reports? I based this on the example in the docs:

class Category < ActiveRecord::Base    has_many :link_posts, class_name: "Link"    has_many :text_posts, class_name: "Text"  end    class Link < ActiveRecord::Base    belongs_to :category    has_many :reports, as: :reportable  end    class Text < ActiveRecord::Base    belongs_to :category    has_many :reports, as: :reportable  end    class Report < ActiveRecord::Base    belongs_to :reportable, polymorphic: true  end  

If I do something like that I would have to use a hacky method to retrieve them:

class Category < ActiveRecord::Base    def reports      reports = []        reports << Report.where(reportable: self.link_posts.to_a)      reports << Report.where(reportable: self.text_posts.to_a)        reports    end  end  

What's the proper way?

Passing custom arguments to Sidetiq

Posted: 17 Jul 2016 07:32 AM PDT

I have a Rails app that requires the user to pass in input that defines how frequently an action is scheduled (e.g one month, three months, six months, etc.) I'm using Sidekiq to run backup jobs, and integrated Sidetiq for the scheduling. As it turns out (something I realized only after integrating it fully), Sidetiq has problems with recurring tasks that initially require custom input. It will run fine the first time, but when it comes up to run three months later, the arguments the method has are (time_last_run, time_of_next_run) and this is a problem for me because I need some user details passed into the recurring action. This is discussed by Sidetiq's author in this issue from a few years ago: https://github.com/tobiassvn/sidetiq/issues/37

This leaves me rather lost. This is my first Rails app, and I'm not sure how else to perform recurring background tasks with user input. As you can see, the Sidetiq issue still hasn't been resolved, and I'm not sure of any valid alternatives. Does anyone know how I can write a workaround for this? Put another way, how else could I implement this functionality (with or without Sidetiq)?

rspec tests in docker showing database transactions

Posted: 17 Jul 2016 07:20 AM PDT

I'm developing a rails app with docker compose and 4 different services: the app, postgres, redis and sidekiq. my problem is that docker compose run app rake spec puts all database transactions to stdout, not just the test output. as a result they are basically unintelligible.

I've tried running this with docker-compose run e RAILS_ENV=test app rake spec and i'm open to the possibility that something else in my spec config that has changed since i started dockerizing- but i just checked out my pre-docker commit and specs ran fine with regular output.

Ruby on Rails, Select Users with age range from Active Record

Posted: 17 Jul 2016 07:11 AM PDT

User.rb

# Attributes  # (..)  # birthdate (string)  #  format "mm/yyyy"    def age    dob = self.birthdate.to_date    now = Time.now.utc.to_date    now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)  end  

In the console:

irb(main):002:0> current_user.age  => 7  

I'd be able to do the following:

age_range = "25-65"  User.where(:age => between age_range)  

I'm stuck at the point how to get the value from age (class method) into the where call

Unicorn, can't restart: "rack and Rack::Builder must be available for processing config.ru"

Posted: 17 Jul 2016 06:52 AM PDT

I have an Ubuntu 14.04 server with nginx and unicorn. I have deployed a Rails application with capistrano to /home/rails/myapp.

When trying to restart unicorn with sudo service unicorn restart I get the following:

* Restarting Unicorn web server unicorn  rack not available, functionality reduced  rack and Rack::Builder must be available for processing config.ru  

I'm getting a 502 from nginx when trying to access the site in my browser.

Here's my /etc/default/unicorn file:

# Change paramentres below to appropriate values and set CONFIGURED to yes.  CONFIGURED=yes    # Default timeout until child process is killed during server upgrade,  # it has *no* relation to option "timeout" in server's config.rb.  TIMEOUT=60    # Path to your web application, sh'ld be also set in server's config.rb,  # option "working_directory". Rack's config.ru is located here.  APP_ROOT=/home/rails/myapp/current    # Server's config.rb, it's not a rack's config.ru  CONFIG_RB=/etc/unicorn.conf    # Where to store PID, sh'ld be also set in server's config.rb, option "pid".  PID=/home/rails/myapp/current/pids/unicorn.pid  RAILS_ENV="production"  UNICORN_OPTS="-D -c $CONFIG_RB -E $RAILS_ENV"    PATH=/usr/local/rvm/rubies/ruby-2.3.0/bin:/usr/local/sbin:/usr/bin:/bin:/sbin:/usr/local/rvm/bin:/usr/local/rvm/gems/ruby-2.3.0@global/bin:/usr/local/rvm/gems/ruby-2.3.0/bin/  export GEM_HOME=/usr/local/rvm/gems/ruby-2.3.0  export GEM_PATH=/usr/local/rvm/gems/ruby-2.3.0:/usr/local/rvm/gems/ruby-2.3.0@global  DAEMON=/usr/local/rvm/gems/ruby-2.3.0/wrappers/unicorn  

Here's my /etc/unicorn.conf file:

listen "unix:/var/run/unicorn.sock"  worker_processes 4  user "rails"  working_directory "/home/rails/myapp/current"  pid "/var/run/unicorn.pid"  stderr_path "/var/log/unicorn/unicorn.log"  stdout_path "/var/log/unicorn/unicorn.log"  

Any Ideas? I feel like I have tried everything.

can we manage multiple shopify key in one application?

Posted: 17 Jul 2016 06:50 AM PDT

We want to use multiple Shopify API keys in one shopify rails application and switch these API key run time. We are working on to increase API call by help to multiple API calls. Because of each API key have some limitation calls like 40 call at time.

Searchkick - how to update mappings and settings (rails)

Posted: 17 Jul 2016 06:45 AM PDT

I have a rails application and around 90k products in my database. I updated the model settings and mappings and need to update these in elasticsearch.

When I call Product.reindex, I get a timeout error (Faraday::TimeoutError: Net::ReadTimeout) after 10seconds (I am using also batch_size: 100). When I start reindexing each product using find_in_batches method, it will reindex all products, but will not update settings and mappings.

Is there any other way (maybe simpler) how can I only update settings and mappings of my index without reindexing the records itself (or anything else that would work and would not throw timeout error)?

Here is the model configuration:

searchkick batch_size: 100, settings: {            number_of_shards: 1,            analysis: {              filter: {                hunspell_CZ: {                  type: 'hunspell',                  locale: 'cs_CZ',                  dedup: true,                  recursion_level: 0                },                czechStemmer: {                  type: 'stemmer',                  name: 'czech'                },              #  customWordDelimiter: {              #    type: 'word_delimiter',              #    generate_word_parts: true,              #    generate_number_parts: true,              #    catenate_words: true,              #    catenate_numbers: true,              #    catenate_all: true,              #    split_on_case_change: true,              #    preserve_original: true,              #    split_on_numerics: true,              #    stem_english_possessive: false              #  },                customUnique: {                  type: 'unique',                  only_on_same_position: false                },                czechDucetSort: {                  type: 'icu_collation',                  language: 'cs'                }              },              analyzer: {                myFulltextAnalyzer: {                  type: 'custom',                  tokenizer: 'standard',                  filter: ['lowercase', 'hunspell_CZ', 'czechStemmer', 'customUnique', 'icu_folding'],#'customWordDelimiter',                  char_filter: ['html_strip']                },                ducet_sort: {                  tokenizer: 'keyword',                  filter: ['czechDucetSort']                }              }            }        },        text_middle: [ :cs_product, :ma_product, :en_product, :cs_description, :en_description, :ma_description ],         index_name: "products_v2",         merge_mappings: true,        mappings: {          product: {            properties: {              cs_product: {                  type: "string",                   analyzer: "myFulltextAnalyzer",                   index: "analyzed",                  fields: {                      raw: {                          type: "string",                          analyzer: "ducet_sort",                          index: "not_analyzed"                      }                  }              },              en_product: {                  type: "string",                   analyzer: "myFulltextAnalyzer",                   index: "analyzed",                  fields: {                      raw: {                          type: "string",                          analyzer: "ducet_sort",                          index: "not_analyzed"                      }                  }              },              ma_product: {                  type: "string",                   analyzer: "myFulltextAnalyzer",                   index: "analyzed",                  fields: {                      raw: {                          type: "string",                          analyzer: "ducet_sort",                          index: "not_analyzed"                      }                  }              },              cs_description: {type: "string", analyzer: "myFulltextAnalyzer", index: "analyzed"},              en_description: {type: "string", analyzer: "myFulltextAnalyzer", index: "analyzed"},              ma_description: {type: "string", analyzer: "myFulltextAnalyzer", index: "analyzed"}            }          }        }  

Why is my RSpec not loading Devise::Test::ControllerHelpers?

Posted: 17 Jul 2016 07:49 AM PDT

I'm using Rails 5, and Devise 3.5.1.

Going through a nice (older) book about creating/testing an API, which uses Devise authentication. It was written before Rails 5, so I chose not to use the new api-only version.

Here's my test...

#/spec/controllers/api/v1/users_controller_spec.rb        require 'rails_helper'    describe Api::V1::UsersController, :type => :controller do      before(:each) { request.headers['Accept'] = "application/vnd.marketplace.v1" }      describe "GET #show" do          before(:each) do              @user = FactoryGirl.create :user              get :show, params: {id: @user.id}, format: :json          end          it "returns the information about a reporter on a hash" do              user_response = JSON.parse(response.body, symbolize_names: true)              expect(user_response[:email]).to eql @user.email          end          it { should respond_with 200 }      end  end  

And here's a completely unexpected RSpec error

Devise::MissingWarden:         Devise could not find the `Warden::Proxy` instance on your request environment.         Make sure that your application is loading Devise and Warden as expected and that the `Warden::Manager` middleware is present in your middleware stack.         If you are seeing this on one of your tests, ensure that your tests are either executing the Rails middleware stack or that your tests are using the `Devise::Test::ControllerHelpers` module to inject the `request.env['warden']` object for you.  

So I go here - http://www.rubydoc.info/gems/devise/Devise/Test/ControllerHelpers

and tried this -> include Devise::Test::ControllerHelpers

which didn't help because the file controller_helpers.rb is nowhere in my project

What did I miss here?

Thanks

Rails Devise token and cookie session at same time

Posted: 17 Jul 2016 06:37 AM PDT

I have a rails web which has been using cookie session authentication (devise) from its beginning. Now, we are developing an ionic mobile application which uses the API available from the rails application.

I have considered to use JWT or token authentication for this new application but I can't find a way to combine both authentication methods, cookie and JWT. Also, both applications have different requirements. For example, in the web a user can have concurrent sessions only if he/she has a certain role. On the opposite, in the mobile application it is possible to have concurrent session without any restriction.

I have reading a lot trying to figure how to combine both methods but I can't find the way. Maybe I should consider to use only one of the methods (JWT) or use another approach (doorkeeper).

Rails simple_form with multi belongs_to association

Posted: 17 Jul 2016 05:36 AM PDT

In my app I have lots of model: (products belongs_to creator, creators belongs_to compagnie, compagnies belongs_to SEO, SEOs belongs_to user)

in my first Seoscontroller I have that:

def create   @seo = current_user.seos.build(seo_params)     if @seo.save      redirect_to search_path     else      render :new     end  end  

(Controller work find!)

In the Compagniescontroller I think (but not work:[ )

def create    seo = Seo.find(params[:seo_id])     @compagnie = seo.compagnies.build(compagnie_params)    if @compagnie.save     redirect_to search_path    else     render :new    end  end  

and in my simple_form....

<%= simple_form_for @compagnie(seo_id: seo.id) do |f| %>  <% end %>  

I search a solution for associate my model id to the controller and the simple_form_for

  create_table "seos", force: :cascade do |t|     t.string   "name"     t.string   "surname"     t.datetime "created_at", null: false     t.datetime "updated_at", null: false     t.integer  "user_id"     t.index ["user_id"], name: "index_seos_on_user_id", using: :btree    end      create_table "compagnies", force: :cascade do |t|      t.string   "compagnie_name"      t.string   "address"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.integer  "seo_id"      t.integer  "user_id"      t.index ["seo_id"], name: "index_compagnies_on_seo_id", using: :btree      t.index ["user_id"], name: "index_compagnies_on_user_id", using: :btree    end  

User model

class User < ApplicationRecord      has_many  :seos    has_many  :compagnies  end  

Seo model

class Seo < ApplicationRecord        belongs_to  :user      has_many    :compagnies        validates :name,        presence: true      validates :surname,      presence: true  end  

compagnie model

class Compagnie < ApplicationRecord         belongs_to :user       belongs_to :seo          validates :address,                 presence: true      validates :compagnie_name,          presence: true  end  

form for Seo

            <%= simple_form_for @seo do |f| %>          <div class="search__form--left split-panel--left">              <div class="search__title">                  Seo:              </div>                      <div class="search__section search__section--od">                        <!--Name-->                      <div class="search__field search__departure grouped-input--top">                          <%= f.input :name, placeholder: "name", :input_html => { :class => "add__name-input ember-text-field textfield station-text-field empty station-text-field-- add__input empty" }, label: false %>                      </div>                        <!--Surname-->                      <div class="search__field search__arrival grouped-input--bottom">                          <%= f.input :surname, placeholder: "prenom", :input_html => { :class => "add__name-input ember-text-field textfield station-text-field empty station-text-field-- search__input empty" }, label: false %>                      </div>                  </div>                    <!--Button-->                  <div class="search__button progress-button">                      <%= f.button :submit, "Add", class: "button progress-button--button" %>                  </div>             </div>      <% end %>  

form for compagnie

    <%= simple_form_for @compagnie(seo_id: seo.id) do |f| %>          <div class="search__form--left split-panel--left">              <div class="search__title">                  Seo:              </div>                      <div class="search__section search__section--od">                        <!--Name-->                      <div class="search__field search__departure grouped-input--top">                          <%= f.input :address, placeholder: "address", :input_html => { :class => "add__name-input ember-text-field textfield station-text-field empty station-text-field-- add__input empty" }, label: false %>                      </div>                        <!--Surname-->                      <div class="search__field search__arrival grouped-input--bottom">                          <%= f.input :compagnie_name, placeholder: "compagnie_name", :input_html => { :class => "add__name-input ember-text-field textfield station-text-field empty station-text-field-- search__input empty" }, label: false %>                      </div>                  </div>                    <!--Button-->                  <div class="search__button progress-button">                      <%= f.button :submit, "Add", class: "button progress-button--button" %>                  </div>             </div>      <% end %>  

Thanks

Ruby: why use # not /?

Posted: 17 Jul 2016 06:24 AM PDT

In the following, what is the reason for having #home rather than /home? All others are /help, /about.

Rails.application.routes.draw do    root 'static_pages#home'    get  'static_pages/help'    get  'static_pages/about'  end  

How can I use Twitter API with Ruby on Rails to retreive tweets from a users follower?

Posted: 17 Jul 2016 04:54 AM PDT

Beginner here so please be kind! So im trying to create my first twitter bot and have done the whole post to twitter etc thing, What i'd really like to do now is be able to use my RoR app to retrieve tweets from my followers and be able to search them for a keyword? Also whilst I have seen tutorials online on how to do this, is there a way to use BootStrap to make them more visually appealing? Hope you can help. Thanks

Ruby on rails application with single http endpoint

Posted: 17 Jul 2016 07:27 AM PDT

Can someone explain what "app with single end point" means in term of rails? How do I set up this endpoint?

'rails server' returns error with mysql 5.7.13 on osx elcapitan

Posted: 17 Jul 2016 05:45 AM PDT

I am new to ruby on rails and also to programming. I have followed instructions on the internet and setup rails application. It worked the first time but later when i reopen it and tried to run 'rails server' it doesn't work and returns following error. I would be happy if some one helps me out of this, i have been searching the internet for 5 hours. Thanks.

I am using ruby 2.3.1p112 rails 5.0 mysql 5.7.13 $ rails server

=> Booting Puma

=> Rails 5.0.0 application starting in development on http://localhost:3000

=> Run rails server -h for more startup options Exiting

/Users/bruce/sea/config/routes.rb:6:in `': undefined

method `root' for main:Object (NoMethodError)

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/activesupport-  

5.0.0/lib/active_support/dependencies.rb:287:in `load'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/activesupport-  

5.0.0/lib/active_support/dependencies.rb:287:in `block in load'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/activesupport-  

5.0.0/lib/active_support/dependencies.rb:259:in `load_dependency'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/activesupport-  

5.0.0/lib/active_support/dependencies.rb:287:in `load'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/application/routes_reloader.rb:40:in `block in load_paths'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/application/routes_reloader.rb:40:in `each'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/application/routes_reloader.rb:40:in `load_paths'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/application/routes_reloader.rb:16:in `reload!'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/application/routes_reloader.rb:26:in `block in updater'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/activesupport-  

5.0.0/lib/active_support/file_update_checker.rb:77:in `execute'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/application/routes_reloader.rb:27:in `updater'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/application/routes_reloader.rb:7:in `execute_if_updated'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/application/finisher.rb:119:in `block in '

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/initializable.rb:30:in `instance_exec'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/initializable.rb:30:in `run'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/initializable.rb:55:in `block in run_initializers'

from /Users/bruce/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0  

/tsort.rb:228:in `block in tsort_each'

from /Users/bruce/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0  

/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'

from /Users/bruce/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0  

/tsort.rb:431:in `each_strongly_connected_component_from'

from /Users/bruce/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0  

/tsort.rb:349:in `block in each_strongly_connected_component'

from /Users/bruce/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0  

/tsort.rb:347:in `each'

from /Users/bruce/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0  

/tsort.rb:347:in `call'

from /Users/bruce/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0  

/tsort.rb:347:in `each_strongly_connected_component'

from /Users/bruce/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0  

/tsort.rb:226:in `tsort_each'

from /Users/bruce/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0  

/tsort.rb:205:in `tsort_each'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/initializable.rb:54:in `run_initializers'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/application.rb:352:in `initialize!'

from /Users/bruce/sea/config/environment.rb:5:in `<top (required)>'    from /Users/bruce/sea/config.ru:3:in `require_relative'    from /Users/bruce/sea/config.ru:3:in `block in <main>'    from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/rack-2.0.1/lib  

/rack/builder.rb:55:in `instance_eval'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/rack-2.0.1/lib  

/rack/builder.rb:55:in `initialize'

from /Users/bruce/sea/config.ru:in `new'    from /Users/bruce/sea/config.ru:in `<main>'    from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/rack-2.0.1/lib  

/rack/builder.rb:49:in `eval'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/rack-2.0.1/lib  

/rack/builder.rb:49:in `new_from_string'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/rack-2.0.1/lib  

/rack/builder.rb:40:in `parse_file'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/rack-2.0.1/lib  

/rack/server.rb:318:in `build_app_and_options_from_config'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/rack-2.0.1/lib  

/rack/server.rb:218:in `app'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/commands/server.rb:59:in `app'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/rack-2.0.1/lib  

/rack/server.rb:353:in `wrapped_app'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/commands/server.rb:124:in `log_to_stdout'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/commands/server.rb:77:in `start'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/commands/commands_tasks.rb:90:in `block in server'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/commands/commands_tasks.rb:85:in `tap'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/commands/commands_tasks.rb:85:in `server'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/commands/commands_tasks.rb:49:in `run_command!'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/railties-5.0.0/lib  

/rails/commands.rb:18:in `'

from /Users/bruce/sea/bin/rails:9:in `require'    from /Users/bruce/sea/bin/rails:9:in `<top (required)>'    from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/spring-1.7.2/lib  

/spring/client/rails.rb:28:in `load'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/spring-1.7.2/lib  

/spring/client/rails.rb:28:in `call'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/spring-1.7.2/lib  

/spring/client/command.rb:7:in `call'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/spring-1.7.2/lib  

/spring/client.rb:30:in `run'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/spring-1.7.2/bin  

/spring:49:in `'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/spring-1.7.2/lib  

/spring/binstub.rb:11:in `load'

from /Users/bruce/.rvm/gems/ruby-2.3.1@global/gems/spring-1.7.2/lib

/spring/binstub.rb:11:in `'

from /Users/bruce/sea/bin/spring:13:in `require'    from /Users/bruce/sea/bin/spring:13:in `<top (required)>'    from bin/rails:3:in `load'`enter     from bin/rails:3:in `<main>'  

Execute JS every time on the event of turbolinks load in Rails 5 app

Posted: 17 Jul 2016 05:15 AM PDT

I would like to execute a few lines of js every time turbolinks is loaded(i.e, the page is loaded), not the js from cache, but would like to force run it before the event of turbolinks load, every time. Is that possible?

I'm trying to get rid of FOUC here, by hiding the html body and doing this in app.js.coffee

$(document).on 'turbolinks:load', ->      document.body.style.visibility = 'visible'  

But the FOUC starts kicking in after the 3rd or 4th time of reloading the page.

To see this live in action, here is a link to the website.

Start MySQL when Rails server gets started?

Posted: 17 Jul 2016 02:56 AM PDT

When I start my Rails 4.2 app locally I ofter get this error:

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)  

I then type mysqld on my terminal and everything is fine.

Is there a way to start MySQL automatically every time the server gets started?

I am on Mac OS 10.11.5.

Thanks for any help.

Ruby on Rails: Optimising multiple http requests to another server

Posted: 17 Jul 2016 06:36 AM PDT

My app makes http requests to another server on behalf of users. This question concerns doing this in the optimal way.

The app may need to return the result of many http requests (to foreign server) to a user as quickly as possible. I have used threading to optimise this as best I can. However, I don't know enough to understand what happens when multiple users use the site at once. Bizarrely, when I simulated a few users making requests to the (local) development server at the same time, the response time didn't appear to suffer at all.

I was thinking of making a class that queues http requests and processes them when it can, however, I wouldn't know whether to instantiate it at App level or User level.

The local Web server is webrick and the production server is puma.

Questions:

  1. What happens when multiple users make requests to my site (where, for each request, my site must in turn make multiple requests to another site)?
  2. How do I optimise response times?
  3. Is having the users of my site send requests to the foreign site directly (ajax) a possibility?

Rails app, dashboard routes

Posted: 17 Jul 2016 02:13 AM PDT

I am trying to create a dashboard for my app. It is not a normal admin panel as I am trying to localize each dashboard to separate models. In other words, I have a model Shop. Each shop has_many Products. Each shop has its own Dashboard which allows a user who has a position at this shop to create and edit this shops products. I am struggling when it comes to designing the routes so that when an employee goes to site.com/shops/5/dashboard he enters his/hers shop dashboard and sees all action he/she is allowed to manage(add product, edit product, add employee, edit employee, etc.). Currently, the routes look like this:

resources :shops do   resources :products   resources :positions   resource :dashboard, only: [:show]  end  

How to separate the :new, :edit, :destroy actions in a namespace so that later I can access all dashboard actions? Would the following be unreasonable for my situation?

resources :shops do    resources :products, only: [:show, :index]    resource :dashboard, only: [:show]    namespace :dashboard do      resources :products, only: [:new, :edit, :update, :destroy]      resources :positions    end  end  

Ruby Rails - Where to start my understanding

Posted: 17 Jul 2016 02:56 AM PDT

I'm trying to learn code and currently running through the exercises within codecademy for Rails.

Though I find this a good learning resource, i'm struggling to understand the relevance of the commands etc to "real life", so I can relate to it.

Can anyone recommend "real life" projects to work through on line re. rails, so I can piece all the fundamental pieces together, whilst seeing what my actions do to the outcome project.

Thank you in advance.

Brendan

Correctly filled fields should stay filled after error (Angular)

Posted: 17 Jul 2016 01:26 AM PDT

I have a problem with register fields in my app. This is my views new.html.slim

- if organization    .grid__cell.unit-12-24.unit-10-24--xs      = f.text_field :email_organization,        name: "email_organization",        value: resource.email_organization,        placeholder: current_organization.placeholder_selected ? current_organization.placeholder : 'Email...',        'ng-model' => 'emailOrganization',        class: "ui-input #{resource.email_organization? ? 'ui-input--error' : ''}"  

When I fill others field wrong - correct field email_organization are empty, and when I delete line 'ng-model' => 'emailOrganization' - everything is ok - correct email field stays after error (incorrect fields are empty) - but I don't want to delete this line because I want to use validation for this field. My validation directive validate_email_organization.coffee

angular.module("validators").directive 'validateOrganization', ->    restrict: 'A'    require: 'ngModel'    link: (scope, element, attrs, ctrl) ->      name = attrs['name'] || 'emailOrganization'      scope.$watch attrs.ngModel, (value) ->        unless value          ctrl.$setValidity(name, true)          return          REGEXP = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))$/        ctrl.$setValidity(name, REGEXP.test(value))  

What I did wrong?

How to develop new features for rails app without affecting existing website

Posted: 17 Jul 2016 01:25 AM PDT

I have recently launched version 1 of my web application and it is currently online and im getting a small amount of traffic on a daily basis. I now need to start developing new features for my application and also have the ability to test these features online on heroku without affecting the existing website until the feature is fully developed and ready to go live. How can I do this? Is it as simple as creating a new branch with git? Or is there a way to have a seperate url that only I can access in which I can push these new features and test them out before pushing it to my main site?

Rails database migration fails with “duplicate column name: email”

Posted: 17 Jul 2016 05:30 AM PDT

I am fairly new to Rails and I'm currently installing the devise gem.

When I created a User model and attempted to migrate the database:

$ rails generate devise User  $ rake db:migrate  

I get the following error response:

== 20160717064710 AddDeviseToUsers: migrating =================================  -- change_table(:users)  rails aborted!  StandardError: An error has occurred, all later migrations canceled:    Mysql2::Error: Duplicate column name 'email': ALTER TABLE `users` ADD `email` varchar(255) DEFAULT '' NOT NULL  Tasks: TOP => db:migrate  (See full trace by running task with --trace)  

I'm not exactly sure what a schema is for, but here is a copy of my schema. It's empty, and I thought it was suppose to be until the database is migrated:

ActiveRecord::Schema.define(version: 0) do    end  

And here is a copy of my migration file in db/migrate:

class DeviseCreateUsers < ActiveRecord::Migration[5.0]    def change      create_table :users do |t|        ## Database authenticatable        t.string :email,              null: false, default: ""        t.string :encrypted_password, null: false, default: ""          ## Recoverable        t.string   :reset_password_token        t.datetime :reset_password_sent_at          ## Rememberable        t.datetime :remember_created_at          ## Trackable        t.integer  :sign_in_count, default: 0, null: false        t.datetime :current_sign_in_at        t.datetime :last_sign_in_at        t.string   :current_sign_in_ip        t.string   :last_sign_in_ip          ## Confirmable        # t.string   :confirmation_token        # t.datetime :confirmed_at        # t.datetime :confirmation_sent_at        # t.string       :unconfirmed_email # Only if using reconfirmable              ## Lockable            # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts            # t.string   :unlock_token # Only if unlock strategy is :email or :both            # t.datetime :locked_at                t.timestamps null: false          end            add_index :users, :email,                unique: true          add_index :users, :reset_password_token, unique: true          # add_index :users, :confirmation_token,   unique: true          # add_index :users, :unlock_token,         unique: true        end      end  

I'm fairly new to Rails, so I'm actually quite lost on what this error means. I'm assuming I apparently already have a column named: "email".

Also, I commented out the t.string :email and typed the following:

rails db:rollback  rails db:migrate  

And I get a differnet error:

Mysql2::Error: Key column 'email' doesn't exist in table: CREATE UNIQUE INDEX `index_users_on_email`  ON `users` (`email`)   

Using Appscript with Rails

Posted: 17 Jul 2016 06:22 AM PDT

I've installed the rb-scpt gem in my Rails project and ran bundle. The gem is a fork from rb-appscript.

The following program works when run from Terminal:

#!/usr/bin/env ruby    # List names of playlists in iTunes.    require "rb-scpt"    itu = Appscript.app("iTunes")  p itu.sources[1].user_playlists.name.get  

I created a controller to do the same thing:

class ItunesController < ApplicationController    def play      itu = Appscript.app('iTunes')      play_list = itu.sources[1].user_playlists.name.get      render text(play_list)    end  end  

When I run it, I get an error on line 3:

<NameError: uninitialized constant ItunesController::Appscript>  

What am I missing? I'm sure it's something simple.

How to redirect in ruby on rails app from old sites url

Posted: 17 Jul 2016 04:09 AM PDT

I am updating my site from PHP to Ruby on Rails. How to redirect from old pages?

example:

old page: /index.php?p=v&tag=__some_word__

new page: /tags/__some_word__

Command to start rails server when using Puma + Nginx

Posted: 16 Jul 2016 10:07 PM PDT

I just pushed my Rails app to my remote server using Capistrano. The app is deployed under the deploy user's home directory - /home/deploy/my_app/current/

I'm using puma as a web server and have nginx configured to look for a socket to which it should forward all incoming web traffic. Snippet from my nginx site config file -

upstream app {      server unix:/home/deploy/my_app/shared/sockets/puma.sock fail_timeout=0;  }  

Correspondingly, my puma.rb file uses bind to create the same socket mentioned above.

# config/puma    # Change to match your CPU core count  workers Integer(ENV["PUMA_WORKERS"] || 2)    # Min and Max threads per worker  threads 1, Integer(ENV["PUMA_MAX_THREADS"] || 5)    DEPLOY_ROOT = "/home/deploy/my_app"  app_dir = File.expand_path("../..", __FILE__)  shared_dir = "#{DEPLOY_ROOT}/shared"    # Default to production  port ENV["PORT"] || 3000  rails_env = ENV['RAILS_ENV'] || "production"  environment rails_env    # Set up socket location  bind "unix://#{shared_dir}/sockets/puma.sock"    # Logging  stdout_redirect "#{shared_dir}/log/puma.stdout.log", "#{shared_dir}/log/puma.stderr.log", true    # Set master PID and state locations  pidfile "#{shared_dir}/pids/puma.pid"  state_path "#{shared_dir}/pids/puma.state"  activate_control_app    on_worker_boot do    require "active_record"    ActiveRecord::Base.connection.disconnect! rescue ActiveRecord::ConnectionNotEstablished    ActiveRecord::Base.establish_connection(YAML.load_file("#{app_dir}/config/database.yml")[rails_env])  end  

The last piece is to start my Rails app. What is the command that I should use to start it? I tried

SECRET_KEY_BASE=blahblahblah rails s -e production --daemon  

however this did not create a socket at the path mentioned above. I also confirmed it by trying to hit my URL and nginx threw up a 502 bad gateway.

Should I be using puma -C config/puma.rb instead? What's the difference, I assume rails server starts puma anyway. And how do I get that socket to be created?

Thanks!

EDIT: When I search for the puma process that's running, it tells me it's listening on a TCP port. I'm not sure how that differs from sockets, but could that be the problem?

[01:08:09] deploy:~  > ps aux | grep puma  deploy   12132  0.0  7.6 523736 78160 ?        Sl   00:59   0:00 puma 3.4.0 (tcp://localhost:3000) [/]  deploy   12314  0.0  0.0  14512   936 pts/0    S+   01:08   0:00 grep puma  

How to call Rails ActiveModel.some_class_method from external thread without of connections broking?

Posted: 16 Jul 2016 10:28 PM PDT

I have a Rails (4.2.6) app and my extending class 'lib/messaging.rb':

# lib/messaging.rb  class Messaging      include Singleton      # this method could be called from continous thread from antoher class from 'lib'    def event_starts_today      Thread.new{ Friend.invite }    end      def invitation_accepted(friends)      Thread.new do        # using this to obtain and close connection within the new thread        friends.each do |friend|          ActiveRecord::Base.connection_pool.with_connection do            Friend.find(friend.id).thanks}          end        end    end    end  

which communicates with the class Friend:

# app/models/friend.rb  class Friend < ActiveRecord::Base      def self.invite      free_friends = []      # trying to protect this for calls from external threads      ActiveRecord::Base.connection_pool.with_connection do        free_friend = Friend.where(is_busy: false).to_a      end      Messaging.instance.invitation_accepted free_friends    end      def say_thanks      ...    end  end  

I suggest that I am doing not in the best way, but Your help would help to understand the way))

The problem outstands in exceptions's messages:

  • No connection pool
  • ActiveRecord::ConnectionNotEstablished

I followed pt.3 from recommendations here http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html#method-i-checkout and other publications that leaded me to understanding that if I use a query on an ActiveModel within a separate Thread then I have to close the connection within this thread.

These lead me to using ActiveRecord::Base.connection_pool.with_connection(&block) method.

And there is still something wrong(

I suggest that I need to join Messaging and Friends somehow in Rails way, but I am confused if the only way is to make http requests(and then all the process will be under Rails controlled threads). I can't catch how to move this Messaging under Rails control.

I have also

#conf/initializers/messaging.rb    Messaging.instance.init # this was cut from post but exists  

and

# config/application.rb  module App    class Application < Rails::Application      ...      config.autoload_paths += %W(#{config.root}/lib)    end  end  

The code is abstracted but represents a real issue. In the real could occur thread-in-thread and sequential queries, but I use the #with_connection(&block) and completing queries with #to_a or #find within each of the &block. But something is wrong((..

Thanks more for any help!! I am really in stuck with this(

Value not being persisted on form error

Posted: 16 Jul 2016 09:27 PM PDT

I have a form, that won't persist (or at least fill) the date input when the submission fails.

For example, let's say I have a form that has two inputs, :date and :post. Both inputs are required. If I fill in :post, the form errors saying :date is require, but it persist and fills the :post value when it errors. Which is normal behavior.

If I fill :date and leave :post blank, it errors again. However, this time it won't persist (or at least fill) the :date field when it re-renders the form.

Clearly the :date is being passed through, so not a strong param issue. And I can manually fill in the :date field on error. Setting value for the :date input to params[:form][:date] works, but I shouldn't have to do that. The value is clearly in the params hash, it just isn't being fill when the form errors. Every other value on the form is being set, just not that :date value.

It's not a huge issue, but it is driving me nuts. And as of right now, I'm out of ideas. Any help would be appreciated.

Coffee script event not firing - why not?

Posted: 16 Jul 2016 09:53 PM PDT

I cannot seem to get a coffee script even firing. My code is below - and i hope it will help someone in future.

Question: Why isn't the coffee script firing?

what am i trying to do

  • I'm trying to create a dynamic selection menu, like in Ryan Bates' railcasts: http://railscasts.com/episodes/88-dynamic-select-menus-revised?view=comments
  • I'm trying to create three selection menus. First the user selects the client, then the project, then the building. A client has many projects which has many buildings. Obviously we want to limit user choices otherwise they'd have to choose from over 100 buildings if these results weren't filtered by first selecting the client and then project.

Here is my coffeescript:

    ## This bit works fine      jQuery ->        projects = $('#project_id').html()                        #Gets the project drop down elements        $('#client_id').change ->                                 #If we change our client selection then:          client = $('#client_id :selected').text()               # OBtain the client           options = $(projects).filter("optgroup[label='#{client}']").html() #Filter all projects by client          if options            $('#project_id').html(options)                      # redraw the drop down menu to show only projects by a specific client.          else            $('#project_id').empty()        #This is not firing for some reason ---------------->        $('#project_id').change ->           alert('hello')          buildings = $('#building_id').html()              project = $('#project_id :selected').text()             options1 = $(buildings).filter("optgroup[label='#{project}']").html()          if options1            $('#building_id').html(options1)          else            $('#building_id').empty()  

And here is my form:

<%= form_for(@rate) do |f| %>    <%= render "shared/errors", object: @rate %>      <fieldset>      <ol>        <li class="required">                       <%= 'client_id included' %>          <%= collection_select(:client, :client_id, Client.all, :id, :name, {include_blank: true}, html_options = {:id => 'client_id'} ) %>                          </li>          <li class="required">          <%= "Now for the project" %>          <%= grouped_collection_select :building, :project_id, Client.all, :projects, :name, :id, :name,   {include_blank: true}, html_options = {:id => 'project_id'} %>        </li>          <li class="required">          <%= "Now for the building" %>          <%= grouped_collection_select :rate, :building_id, Project.order(:name), :buildings, :name, :id, :name,   {include_blank: true}, html_options = {:id => 'building_id'} %>        </li>     <!-- The bits in the middle are more or less superfluous '-->        </ol>      <p>        <%= f.submit %>        <%= link_to "Cancel", rates_path, class: 'button' %>      </p>    </fieldset>  <% end %>  

Any idea where the problem is? Any assistance much appreicated.

No comments:

Post a Comment