Friday, September 9, 2016

Error with redirections - Rails | Fixed issues

Error with redirections - Rails | Fixed issues


Error with redirections - Rails

Posted: 09 Sep 2016 07:49 AM PDT

I'm getting the error "404 not found" of my web page when I try to enter to some subdirections, here is the log of the issue:

at=info method=GET path="/ubicacion" host=www.ifurniture.pe request_id=070be6fd-a9b4-46c9-8814-1febafe6ddbc fwd="190.234.105.100" dyno=web.1 connect=0ms service=59ms status=404 bytes=9968  Started GET "/ubicacion" for 190.234.105.100 at 2016-09-08 16:34:00 +0000  Processing by Refinery::PagesController#show as HTML  Parameters: {"path"=>"ubicacion", "locale"=>:es}  [1m[35mRefinery::Page Load (1.7ms)[0m  SELECT  "refinery_pages".* FROM "refinery_pages" INNER JOIN "refinery_page_translations" ON "refinery_page_translations"."refinery_page_id" = "refinery_pages"."id" WHERE "refinery_pages"."parent_id" IS NULL AND "refinery_page_translations"."locale" IN ('es', 'en') AND "refinery_page_translations"."slug" = 'ubicacion'  ORDER BY "refinery_pages"."id" ASC LIMIT 1  [1m[36mRefinery::Page Load (0.9ms)[0m  [1mSELECT  "refinery_pages".* FROM "refinery_pages" WHERE "refinery_pages"."menu_match" = $1  ORDER BY "refinery_pages"."id" ASC LIMIT 1[0m  [["menu_match", "^/404$"]]  Rendered refinery/pages/404.html.erb within layouts/application (0.4ms)  Rendered refinery/_site_bar.html.erb (0.1ms)  [1m[35mRefinery::Page::Translation Load (1.5ms)[0m  SELECT "refinery_page_translations".* FROM "refinery_page_translations" WHERE "refinery_page_translations"."refinery_page_id" = $1  [["refinery_page_id", 2]]  [1m[36mRefinery::Page::Translation Load (1.8ms)[0m  [1mSELECT "refinery_page_translations".* FROM "refinery_page_translations" WHERE "refinery_page_translations"."refinery_page_id" = $1[0m  [["refinery_page_id", 1]]  Rendered refinery/_head.html.erb (18.7ms)  Rendered vendor/bundle/ruby/2.0.0/bundler/gems/refinerycms-80b1db39ad22/core/app/views/refinery/_javascripts.html.erb (0.1ms)  Filter chain halted as :find_page rendered or redirected  Completed 404 Not Found in 54ms (Views: 21.0ms | ActiveRecord: 19.0ms)  

the web page is hosted on Heroku, the logs was take from there.

this is the pages_controller.rb file:

module Refinery    class PagesController < ::ApplicationController      include Pages::RenderOptions      include Productos        before_action :find_page, :set_canonical      before_action :error_404, :unless => :current_user_can_view_page?        # Save whole Page after delivery      after_action :write_cache?        # This action is usually accessed with the root path, normally '/'      def home        @posts = Blog::Post.newest_first.live.includes(:comments, :categories)        render_with_templates?      end        # This action can be accessed normally, or as nested pages.      # Assuming a page named "mission" that is a child of "about",      # you can access the pages with the following URLs:      #      #   GET /pages/about      #   GET /about      #      #   GET /pages/mission      #   GET /about/mission      #      def show        @productos = Refinery::Productos::Producto.all        if should_skip_to_first_child?          redirect_to refinery.url_for(first_live_child.url) and return        elsif page.link_url.present?          redirect_to page.link_url and return        elsif should_redirect_to_friendly_url?          redirect_to refinery.url_for(page.url), :status => 301 and return        end          render_with_templates?      end      protected        def requested_friendly_id        if ::Refinery::Pages.scope_slug_by_parent          # Pick out last path component, or id if present          "#{params[:path]}/#{params[:id]}".split('/').last        else          # Remove leading and trailing slashes in path, but leave internal          # ones for global slug scoping          params[:path].to_s.gsub(%r{\A/+}, '').presence || params[:id]        end      end        def should_skip_to_first_child?        page.skip_to_first_child && first_live_child      end        def should_redirect_to_friendly_url?        requested_friendly_id != page.friendly_id || (          ::Refinery::Pages.scope_slug_by_parent &&          params[:path].present? && params[:path].match(page.root.slug).nil?        )      end        def current_user_can_view_page?        page.live? || authorisation_manager.allow?(:plugin, "refinery_pages")      end        def first_live_child        page.children.order('lft ASC').live.first      end        def find_page(fallback_to_404 = true)        @page ||= case action_name                  when "home"                    Refinery::Page.find_by(link_url: '/')                  when "show"                    Refinery::Page.friendly.find_by_path_or_id(params[:path], params[:id])                  end        @page || (error_404 if fallback_to_404)      end        alias_method :page, :find_page        def set_canonical        @canonical = refinery.url_for @page.canonical if @page.present?      end        def write_cache?        # Don't cache the page with the site bar showing.        if Refinery::Pages.cache_pages_full && !authorisation_manager.allow?(:read, :site_bar)          cache_page(response.body, File.join('', 'refinery', 'cache', 'pages', request.path).to_s)        end      end    end  end  

this is the ubicacion.html.erb file:

<section class="background-image">    <div class="container">      <h1>Frase de fuerza aquí</h1>    </div>  </section>  <section class="map container">    <h2>Ubícanos</h2>    <div class="left">      <article class="address" id="direccion1">        <span>Dirección 1</span>        <ul>          <li><i class="fa fa-map-marker"></i> Av. Nombre de la Calle 111 Departamento - Perú</li>          <li><i class="fa fa-phone"></i> (01)-2222222</li>        </ul>      </article>      <article class="address" id="direccion2">        <span>Dirección 2</span>        <ul>          <li><i class="fa fa-map-marker"></i> Av. Nombre de la Calle 111 Departamento - Perú</li>          <li><i class="fa fa-phone"></i> (01)-2222222</li>        </ul>      </article>      <article class="address" id="direccion3">        <span>Dirección 3</span>        <ul>          <li><i class="fa fa-map-marker"></i> Av. Nombre de la Calle 111 Departamento - Perú</li>          <li><i class="fa fa-phone"></i> (01)-2222222</li>        </ul>      </article>    </div>    <div class="right" id="overlay"><iframe id="map" src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d3311.4313418937313!2d-75.75184435164877!3d-14.046904027645624!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2spe!4v1448313155975" height="450" frameborder="0" style="border:0" allowfullscreen></iframe></div>  </section>  <section class="register">    <div class="container">      <h2>Regístrate para recibir</h2>      <%= form_tag '/suscribir', target: "_top" do %>        <%= hidden_field_tag :group_name, 'suscriptores' %>        <%= hidden_field_tag :group, 'newsletter' %>        <%= text_field_tag :first_name, nil, type: "text", placeholder: "Nombre" %>        <%= text_field_tag :email, nil, type: "email", placeholder: "Email", pattern: "[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$", required: true %>      <%= submit_tag "Enviar" %>      <% end %>    </div>  </section>  

The issue is too in other subdirections, I'll watch for your answers.

bootstrap datetimepicker bug

Posted: 09 Sep 2016 07:48 AM PDT

I have got a problem with a bootstrap datetimepicker. If I select for example 14:00, the component set time to 2:00 and it can´t change it. I have got a cs locale. This bug is only in hour, minutes view without a date.

Screenshot: https://postimg.org/image/q4km0c5r5/

Have you got any idea please?

Filter using ransacker

Posted: 09 Sep 2016 07:42 AM PDT

I am using the next code to get a simple filter at the column created_at of the table A

ransacker :by_resolved_at_in do Arel::Nodes::SqlLiteral.new("created_at") end

This works fine. Now I want to extend my filter using a inner join with table B on A.id=B.id where B.column="x". Could you help me with the sintax to put this query in SqlLiteral?

seed_fu seeding multiple times

Posted: 09 Sep 2016 07:38 AM PDT

I have the following tables:

create_table "fee_parameters", force: :cascade do |t|    t.integer  "fee_type_id",    limit: 4    t.string   "name",           limit: 255    t.string   "value",          limit: 255    t.string   "parameter_type", limit: 255    t.datetime "created_at",                 null: false    t.datetime "updated_at",                 null: false  end    create_table "fee_rules", force: :cascade do |t|    t.integer  "fee_suite_id",     limit: 4    t.integer  "fee_parameter_id", limit: 4    t.string   "name",             limit: 255    t.float    "multiplier",       limit: 24    t.float    "addend",           limit: 24    t.datetime "created_at",                   null: false    t.datetime "updated_at",                   null: false  end  

Models look like this:

class FeeParameter < ActiveRecord::Base    has_one :fee_rule    belongs_to :fee_type  end    class FeeRule < ActiveRecord::Base    belongs_to :fee_suite    belongs_to :fee_parameter      def self.strong_params_array(params)      params.keys.map{|key| key.to_sym}    end  end  

my seed file looks like this:

FeeParameter.seed_once(:name, :value, :parameter_type, :fee_type_id) do |f|    f.name = 'Visa subtotal'    f.value = 'visa'    f.parameter_type = 'currency'    f.fee_type_id = 1  end    FeeRule.seed_once(:fee_suite_id, :name, :fee_parameter_id, :multiplier, :addend) do |f|    f.fee_suite_id = 1    f.name = "test"    f.fee_parameter_id = 1    f.multiplier = 0.045    f.addend = 0  end  

For some reason FeeParameter is created just once even after running seed_fu multiple times. But FeeRule creates a new, identical entry in the table every time I run seed_fu.

Sort json data alphabetically in ruby on rails

Posted: 09 Sep 2016 07:52 AM PDT

I have this data with me:

[{:id=>250,        :application_date=>"02/04/2016",        :customer_number=>"",        :customer_name=>"Neymar Silva Junior",        :city=>"Auckland",        :region=>"Auckland",        :service=>"Electricity",        :name=>"Bosco and Sons",        :service_plan=>"Electricity Plan",        :connection_type=>nil,        :billing_method=>nil,        :icp_number=>nil,        :moving_date=>"",        :supplier_commission=>21.0,        :show_url=>"/applications/250"},   {:id=>257,        :application_date=>"27/05/2016",        :customer_number=>"",        :customer_name=>"Ariel name Parra",        :city=>"Dunedin",        :region=>"Dunedin",        :service=>"Electricity",        :name=>"Bosco and Sons",        :service_plan=>"Electricity Plan",        :connection_type=>nil,        :billing_method=>nil,        :icp_number=>nil,        :moving_date=>"28/05/2016",        :supplier_commission=>21.0,        :show_url=>"/applications/257"},   {:id=>291,        :application_date=>"29/04/2016",        :customer_number=>"aaaa",        :customer_name=>"Neymar Silva Junior",        :city=>"Auckland",        :region=>"Auckland",        :service=>"Electricity",        :name=>"Bosco and Sons",        :service_plan=>"Electricity Plan",        :connection_type=>nil,        :billing_method=>nil,        :icp_number=>"",        :moving_date=>"",        :supplier_commission=>28.0,        :show_url=>"/applications/291"},   {:id=>292,        :application_date=>"29/04/2016",        :customer_number=>"23223",        :customer_name=>"Neymar Silva Junior",        :city=>"Auckland",        :region=>"Auckland",        :service=>"Electricity",        :name=>"Bosco and Sons",        :service_plan=>"Electricity Plan",        :connection_type=>nil,        :billing_method=>nil,        :icp_number=>"",        :moving_date=>"",        :supplier_commission=>21.0,        :show_url=>"/applications/292"}]  

I want to sort this data in two different ways, alphabetically(from A to Z) as well as Recursively(Z to A) according to its attributes in following scenarios:

  1. If the sort parameter is service_plan alphabetically it will sort as per this attribute from A to Z, if recursively then Z to A for this attribute and so on for all attributes.

  2. Id is integer so it should be sorted in increasing or decreasing order.

  3. Moreover the nil value should not through an error and should be present in the result.

Thanks in advance!

No confirmation paths / controller devise rails

Posted: 09 Sep 2016 07:34 AM PDT

i installed the devise gem and including the confirmable module but when i try to register it doesn't ask for a confirmation. When i type rake routes it shows just this;

                  Prefix Verb   URI Pattern                        Controller#Action          new_user_session GET    /gebruiker/sign_in(.:format)       devise/sessions#new              user_session POST   /gebruiker/sign_in(.:format)       devise/sessions#create      destroy_user_session DELETE /gebruiker/sign_out(.:format)      devise/sessions#destroy             user_password POST   /gebruiker/password(.:format)      devise/passwords#create         new_user_password GET    /gebruiker/password/new(.:format)  devise/passwords#new        edit_user_password GET    /gebruiker/password/edit(.:format) devise/passwords#edit                           PATCH  /gebruiker/password(.:format)      devise/passwords#update                           PUT    /gebruiker/password(.:format)      devise/passwords#update  cancel_user_registration GET    /gebruiker/cancel(.:format)        devise/registrations#cancel         user_registration POST   /gebruiker(.:format)               devise/registrations#create     new_user_registration GET    /gebruiker/sign_up(.:format)       devise/registrations#new    edit_user_registration GET    /gebruiker/edit(.:format)          devise/registrations#edit                           PATCH  /gebruiker(.:format)               devise/registrations#update                           PUT    /gebruiker(.:format)               devise/registrations#update                           DELETE /gebruiker(.:format)               devise/registrations#destroy  

As you can see no confirmation/new (gebruiker stands for user)

But i did get a confirmation/new view when doing rails g devise:views

And in my schema.rb you can see that the confirmable module is definitely added:

  create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      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"      t.string   "confirmation_token"      t.datetime "confirmed_at"      t.datetime "confirmation_sent_at"      t.string   "unconfirmed_email"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false    end  

This was the migration file;

class DeviseCreateUsers < ActiveRecord::Migration    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  

How can i bring back the confirmation_paths ?

Rails - How can I select records and those records has_many children without the query returning duplicates

Posted: 09 Sep 2016 07:27 AM PDT

given these models

ModelOne      has_many :model_twos    ModelTwo      belongs_to :model_one        string :field_one  

and given these records

model_twos      id  field_one  model_one_id      1  "val 1"     1      2  "val 2"     1      3  "val 3"     1      4  "val 4"     2      5  "val 5"     2      6  "val 6"     2  

how can I retrieve all model_ones and those model_ones model_twos field_one values in one query without it returning 3 instances of each model_one

I've tried various permutations of ModelOne.joins("LEFT JOIN model_twos ON model_twos.model_one_id = model_ones.id").select("DISTINCT model_ones.*, model_twos.field_one as model_two_field_one") but none give the result I'm looking for

I'd like a rails way to do it, but I would also be happy with a sql query that would work

simple association works in console but not in application

Posted: 09 Sep 2016 07:23 AM PDT

I am trying to use a simple association to show user.email for workflows.

 def mail_notify_engineering      @workflow = Workflow.where("Title like ?", "Engineer")      @workflow = @workflow.first      $temp1 = @workflow      $temp2 = @workflow.user.email  

When I run that, I get

NoMethodError in ApplicationController#notify_engineering  undefined method `email' for #<Workflow:0xb1ba8b8>    Rails.root: C:/Users/cmendla/RubymineProjects/product_development    Application Trace | Framework Trace | Full Trace  app/mailers/application_mailer.rb:37:in `mail_notify_engineering'  app/controllers/application_controller.rb:19:in `notify_engineering'  Request    Parameters:    None  

However, if I run the commands in the console, it seems to work.

>> @workflow = Workflow.where("Title like ?", "Engineer")    Workflow Load (3.0ms)  EXEC sp_executesql N'SELECT [pd].[workflows].* FROM [pd].[workflows] WHERE (Title like N''Engineer'')'  #<ActiveRecord::Relation [#<Workflow id: 3, title: "Engineer", user_id: 1, created_at: "2016-09-02 18:28:29", updated_at: "2016-09-02 18:28:29">]>  >> @workflow = @workflow.first  #<Workflow id: 3, title: "Engineer", user_id: 1, created_at: "2016-09-02 18:28:29", updated_at: "2016-09-02 18:28:29">  >> $temp2 = @workflow.user.email  "christopher.mendla@ccttapes.com"    User Load (2.0ms)  EXEC sp_executesql N'SELECT  [pd].[users].* FROM [pd].[users] WHERE [pd].[users].[id] = @0  ORDER BY [pd].[users].[id] ASC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY', N'@0 int', @0 = 1  [["id", 1]]  

The two models are:

class Workflow < ActiveRecord::Base    belongs_to :user, :class_name => 'Workflow', foreign_key: 'user_id'      validates_presence_of :title    validates_presence_of :user_id      validates_uniqueness_of :title, :scope => :user_id    end        class User < ActiveRecord::Base    has_many :workflows  

The tables are

TABLE pd.workflows (       id INT IDENTITY NOT NULL,       title NVARCHAR(4000) NULL,       [user_id] INT NULL,       created_at DATETIME NOT NULL,       updated_at DATETIME NOT NULL,       CONSTRAINT PK__workflow__3213E83FA1246A13 PRIMARY KEY (id)  )      TABLE tl.users (       id INT IDENTITY NOT NULL,       login VARCHAR(50) NULL,       group_strings TEXT NULL,       name VARCHAR(50) NULL,       ou_strings VARCHAR(150) NULL,       created_at DATETIME NOT NULL,       updated_at DATETIME NOT NULL,       email VARCHAR(50) NULL,       signature TEXT NULL,       operating_system VARCHAR(50) NULL,       notes_path VARCHAR(50) NULL,       client VARCHAR(50) NULL,       outlook_path VARCHAR(150) NULL,       CONSTRAINT PK_users PRIMARY KEY (id)  )  

If the association works in console, why isn't it working when run as an app?

Rails: How to check the number of each do

Posted: 09 Sep 2016 06:49 AM PDT

I'd like to know the number of each do in view.

For example,

  <% schedule.rooms.each do |r| %>      <% r.events.each do |e| %>  

If there is no r.events, I'd like to add something.

  <% schedule.rooms.each do |r| %>      <% r.events.each do |e| %>        <% if _r.events is not exist_ %>          do something  

It would be appreciated if you could give me any advice.

how to rescue from AbstractController::ActionNotFound exception in Rails 5?

Posted: 09 Sep 2016 06:36 AM PDT

In my application controller I am rescuing from a bunch of different exceptions to display my own error page with no problem. For example:

rescue_from ActiveRecord::RecordNotFound, with: :not_found  rescue_from ActionView::MissingTemplate, with: :server_error  # etc...  

However the following does not work:

rescue_from AbstractController::ActionNotFound, with: :not_found  

Which I understand is because the exception is raised in AbstractController before we get to my application controller to be able to rescue it.

I would like to be able to rescue from this exception too and I haven't been able to find a solution that works.
I've tried sending exception to the router by doing:

config/application.rb

config.exceptions_app = self.routes  

and in config/routes.rb

get "*any", via: :all, to: "application#not_found"  

which does not work and seems to be the most common answer for Rails 3 and 4. I'm using Rails 5.0.0 and any help is appreciated

Getting Sass::SyntaxError: Invalid UTF-8 character "\xE3" in production

Posted: 09 Sep 2016 06:56 AM PDT

I'm able to compile assets successfully through the development environment by the following command:

bundle exec rake assets:precompile RAILS_ENV=development  

However, when I compile the same set of assets through production environment, it throws the following error:

Sass::SyntaxError: Invalid UTF-8 character "\xE3"  

I do have a file where there is some Japanese written like this:

content: "必須";  

I have commented this thing out, but it doesn't make any difference.

What I have tried:

I have put @charset "UTF-8"; at the very top of each file, but still I'm getting the same error. I have also used Rails.application.config.assets.precompile with = sign instead of += on multiple lines according to a Stackoverflow question, but it didn't help either.

I'm using Rails 5.0, and ruby 2.2.3.

For assets, I'm using the following gems:

gem 'uglifier', '>= 1.3.0'  gem 'bootstrap-sass', '~> 3.3.6'  gem 'sass-rails', '>= 3.2'  

rails nested attributes creating, but not updating and not deleting

Posted: 09 Sep 2016 06:44 AM PDT

I have following models:

class Company < ActiveRecord::Base    has_and_belongs_to_many :people    has_many :companies_people      accepts_nested_attributes_for :companies_people, allow_destroy: true, reject_if: :all_blank  end    class CompaniesPerson < ActiveRecord::Base    belongs_to :company    belongs_to :person    belongs_to :company_role  end    class Person < ActiveRecord::Base  end    class CompanyRole < ActiveRecord::Base  end  

and I'm trying along with Company object to update it's companies_people associated objects. The issue I'm facing is that I can create new companies_people objects but not update or remove existing ones. And what is the most thrilling is that it's not another question about not permitted or missing :id and :_destroy params - I have those set up for sure, but still can't nor update nor delete an existing association.

Eg. this call which has a purpose of updating company_role_id from 1 to 2 is being totally ignored:

Company.first.update_attributes(companies_people_attributes: [{id: 1, person_id: 1, company_role_id: 2}])  

ps. tested with Rails 4.2.4

SimpleCov not showing rails files

Posted: 09 Sep 2016 07:14 AM PDT

I'm trying to use simplecov to monitor my test coverage however after having to roll back some changes to my project and reinstall simplecov it seems to have broken.

It no longer tracks the models and controller ect, but instead covers the spec files, as can be seen here:

enter image description here

How can I get it back to how it should be where it's tracking the actual rails files in separate tabs?

Any help would be great!

Routing error page rendering routes partial more than 2 thousand times

Posted: 09 Sep 2016 06:20 AM PDT

I'm upgrading a project from Ruby 1.9.3 and Rails3 to Ruby 2.2.2 and Rails 5.0.0.1. This problem didn't happen before with the old config.

Every time I have a routing error, the response takes around 2 seconds because the "routes" partial

ActionController::RoutingError (No route matches [GET] "/banner_mids/original/missing.png"):    actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:53:in `call'  web-console (3.3.1) lib/web_console/middleware.rb:131:in `call_app'  web-console (3.3.1) lib/web_console/middleware.rb:28:in `block in call'  web-console (3.3.1) lib/web_console/middleware.rb:18:in `catch'  web-console (3.3.1) lib/web_console/middleware.rb:18:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'  railties (5.0.0.1) lib/rails/rack/logger.rb:36:in `call_app'  railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `block in call'  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `block in tagged'  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:26:in `tagged'  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `tagged'  railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `call'  request_store (1.3.1) lib/request_store/middleware.rb:9:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call'  rack (2.0.1) lib/rack/method_override.rb:22:in `call'  rack (2.0.1) lib/rack/runtime.rb:22:in `call'  activesupport (5.0.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/static.rb:136:in `call'  rack (2.0.1) lib/rack/sendfile.rb:111:in `call'  railties (5.0.0.1) lib/rails/engine.rb:522:in `call'  rack (2.0.1) lib/rack/handler/webrick.rb:86:in `service'  /home/arielau/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'  /home/arielau/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'  /home/arielau/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'    Rendering /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb within rescues/layout    Rendering /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb    Rendered /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.7ms)    Rendered collection of /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_route.html.erb [2639 times] (1237.2ms)    Rendered collection of /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_route.html.erb [6 times] (2.8ms)    Rendered /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_table.html.erb (2.5ms)    Rendering /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb    Rendered /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.8ms)    Rendered /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb within rescues/layout (2066.0ms)  

As you can see, it takes 2 seconds just to respond, because it's rendering the _routes partial more than 2 thousand times!!!

Rendered collection of /home/arielau/.rvm/gems/ruby-2.2.2/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_route.html.erb [2639 times] (1237.2ms)  

It only happens if I request an asset, other routing errors works fine.

The worst consecuence is that many requests to missing assets takes so much time that other requests times out and an error message about some pool size thing being all taken after 5.01 seconds of waiting.

If it's a normal behavior, a workaround for me would be not to render the routes table on the routing error page since I don't really need it, can I do that at least?

EDIT: it's always rendering that partial 2639 times and 6 more times on the next line, my project has 2648 routes (it's a big big project), I guess that's where the problem begins

Merging parameters rails

Posted: 09 Sep 2016 06:06 AM PDT

in my rails app, a user can select other users they'd like to join a 'party' with. I'm trying to merge the current user's ID with those that the user has selected. This is one way i've tried:

def party_params     params.require(:party).permit(:length, :game_id, user_ids: []).merge("user_ids" => ["user_ids"] + [current_user.id])  end  

This comes back with :

Couldn't find all Users with 'id': (0, 17) (found 1 results, but was looking for 2)

Doing .merge(:user_ids => [current_user.id]) instead results in the party only being created with the current user and removing all the selected users.

I've also tried moving the .merge to a function and calling it on new, but that doesn't seem to work either.

In my models a party has_and_belongs_to_many :users and likewise a user has_and_belongs_to_many :parties

Any help appreciated! Thanks.

rails method as a function

Posted: 09 Sep 2016 07:30 AM PDT

This has probably been asked before but I cannot find any info on this

I am using I18n with 2 locales en and ja

Trying to fetch data from a table that has columns like title_en title_ja. So when locale is en title_en should be shown

Is there a short way to do this in ruby?

I am trying to use helpers:

module WorksHelper      def col_lang(col)          if (locale == :ja)              lang = "_ja"          else              lang = "_en"          end          return col+lang      end  end  

And then I cant figure out a way to call this in the views. I am trying this:

<%= work.(col_lang("title")) %>  

but obviously this is wrong. Ruby says undefined method call . How do I call the function here?

Log rails console always to file in production env

Posted: 09 Sep 2016 05:37 AM PDT

As you maybe know by yourself, sometimes you have to do tasks on a live production machine, via the rails console...

I usually start it with: bundle exec rails console -e production

But since its the production machine, I would like to log all in+outputs of the rails console to a file, f.e. to /home/sshuser/myproject/console_sessions/2016_09_09__14_33_33.txt

Anybody knows how to do this? I would like to start the logger atuomatically, but only if I run the console?

(I'm running Rails 3.2) Thanks!

Search through multiple attributes within a json data in rails

Posted: 09 Sep 2016 05:49 AM PDT

I have this incoming data which I need to search.

[{:id=>250,      :application_date=>"02/04/2016",      :customer_number=>"",      :customer_name=>"Neymar Silva Junior",      :city=>"Auckland",      :region=>"Auckland",      :service=>"Electricity",      :name=>"Bosco and Sons",      :service_plan=>"Electricity Plan",      :connection_type=>nil,      :billing_method=>nil,      :icp_number=>nil,      :moving_date=>"",      :supplier_commission=>21.0,      :show_url=>"/applications/250"},   {:id=>257,      :application_date=>"27/05/2016",      :customer_number=>"",      :customer_name=>"Ariel name Parra",      :city=>"Dunedin",      :region=>"Dunedin",      :service=>"Electricity",      :name=>"Bosco and Sons",      :service_plan=>"Electricity Plan",      :connection_type=>nil,      :billing_method=>nil,      :icp_number=>nil,      :moving_date=>"28/05/2016",      :supplier_commission=>21.0,      :show_url=>"/applications/257"},   {:id=>291,      :application_date=>"29/04/2016",      :customer_number=>"aaaa",      :customer_name=>"Neymar Silva Junior",      :city=>"Auckland",      :region=>"Auckland",      :service=>"Electricity",      :name=>"Bosco and Sons",      :service_plan=>"Electricity Plan",      :connection_type=>nil,      :billing_method=>nil,      :icp_number=>"",      :moving_date=>"",      :supplier_commission=>28.0,      :show_url=>"/applications/291"},   {:id=>292,      :application_date=>"29/04/2016",      :customer_number=>"23223",      :customer_name=>"Neymar Silva Junior",      :city=>"Auckland",      :region=>"Auckland",      :service=>"Electricity",      :name=>"Bosco and Sons",      :service_plan=>"Electricity Plan",      :connection_type=>nil,      :billing_method=>nil,      :icp_number=>"",      :moving_date=>"",      :supplier_commission=>21.0,      :show_url=>"/applications/292"}]  

I have been able to achieve this.

Store that data in a variable s

s.select {|h1| h1[:service_plan]=='Electricity Plan'}  

Now this gives me all those elements which has the matching service_plan.

What I want to achieve.

  1. If I search with only few words like Elec not the entire word it should show the same result.
  2. This search should be applied to multiple attributes and not restrict to only one attribute like service_plan.

I want to exactly achieve something which we used to do in Rails active_record like this:

Model.where('attribute_one LIKE :search OR attribute_two LIKE :search OR attribute_three LIKE :search', search: "%#{search}%")  

OR

Model.find(:all, :conditions => ['attribute_one LIKE ? OR attribute_two LIKE ? OR attribute_three LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%"])  

where search is the incoming search parameter.

I want to achieve the same kind of result in a json data.

Thanks in advance!

how to redirect second last page

Posted: 09 Sep 2016 05:30 AM PDT

Thanks for reading my question,

in my application i need to save state of url in which i need to store request path 2ed last request, i know request.reffer is return last page url but i need to 2ed last page url ,how can i achieve this without routes modification and without any params is this possible to achieve this kind of stuff

scenario:

suppose i have some authenticated page for checkout now 1.user can access product page without authentication 2.but when user need to buy product he need to login or signup 3.with login i can achieve redirect back to product path 4.but signup link is available on signing page so request.reffer will return signin path after signup

Any good suggestion is also welcome

[Rails][mongoid] Can I edit mongo oplog events?

Posted: 09 Sep 2016 05:26 AM PDT

Hi i am new to all mongodb environment.

I have to build a service that watches database events, and send them to other services, knowing that my service is only a watcher and has no responsibility of editing them.

So I have used the Oplog system and it's working fine.

The problem is that when an entry is deleted i have a message like:

{"ts"=>#<BSON::Timestamp:0x00000001e8aa70 @seconds=1473415247, @increment=1>, "h"=>-8600745338823431584, "v"=>2, "op"=>"d", "ns"=>"apiv3_production.cloud_subscriptions", "b"=>true, "o"=>{"_id"=>BSON::ObjectId('57a8964407950f5d6100000d')}}  

and I need for serialization some data in my cloud_subscriptions model, and as the entry have been deleted i can't fetch it in database no more, so I have googled this for a while now with no way of finding this.

What i need is to edit the "o" hash of the message to add the information i need, is this possible ?

My configuration is rails 4, mongoid 5, mongodb 2.6.

undefined method two_dimensional? barby barcodes

Posted: 09 Sep 2016 05:34 AM PDT

I'm using Barby to generate EAN13 Barcodes.

I'm getting the error: undefined method two_dimensional?' for "400000000000":String

The code i'm using in the controller:

def index    @barcode = getnumber    @barcode_voorbeeld = Barby::HtmlOutputter.new(@barcode)    @barcode_voorbeeld.to_html  end    def getnumber    Barcode.first.number  end  

In the end what I want to accomplish is to get the last Barcode model and add + 1 to the number, so something like @barcode = getnumber + "1" and the result of this should be in this case 400000000001

thanks in advance.

CSS identifiers in ActionMailer

Posted: 09 Sep 2016 04:51 AM PDT

I am working on a project whereby there are two different customers for the application and based on a user's credentials when they log in one of two css classes are applied (CustomerA & CustomerB). The classes hide and show information based on these credentials. This works okay in the main application but when an email template uses this approach there are problems in that both are applied. Is there any way to apply these style rules to the email body as well.

observer

def after_save(campaign)    if campaign.status_changed? && campaign.status == 'Approved'      CampaignMailer.campaign_approved(campaign).deliver!    elsif campaign.status_changed? && campaign.status == 'Rejected'      CampaignMailer.campaign_rejected(campaign).deliver!  end  

mailer

def campaign_approved(campaign)    @host = Portal.host_for_operator(campaign.operator)    @campaign = campaign    mail(:to => [campaign.partner.contact_email] + admins, :subject => "Your Campaign '#{campaign.name}' Has Been Approved", template_path: 'mailers/campaign_mailer', template_name: 'campaign_approved')  end  

template

.companyA      Company A text    .companyB      Company B text  

Geocoder gem rails rake geocode dont work

Posted: 09 Sep 2016 04:50 AM PDT

I have an app with geocoder gem installed. System work perfectly for one edit/update entry. I m trying to bulk geocode all objects (+6500) from my database with rake geocode:all. When i run the command nothing happen... Adress wasnt geocode. I don't know why. Can you help me ? Thanks.

Camping.rb

geocoded_by :fulladress  after_validation :geocode      def fulladress      [adresse,code_postale,commune].to_a.compact.join(",")    end  

How can I upload thumb versions of images that already exist into a different db record in carrierwave

Posted: 09 Sep 2016 04:48 AM PDT

I'm creating thumb versions of new images being uploaded and keeping the original file as well. But I've only just added this into my app and there are like 600 images already uploaded over time that don't have thumb versions. I want the images already uploaded to have thumbs as well.

I can see from reading the carrierwave docs that you can run a script to re upload images in the DB to be a different size. But this replaces the original image with the newly sized image.

Is there a way for me to do something similar to what they have there in the docs but save it to the image_thumb column and not replace the image in the original_image column? Basically run through the original_image column, resizing them and saving it to the image_thumb column.

I'm using MiniMagick incase that helps.

Rails / Stripe - taking multiple payments

Posted: 09 Sep 2016 06:51 AM PDT

I'm building an events app using Rails and Stripe to handle payments. I've used javascript for my booking page in order to allow a user to book and pay for multiple spaces rather than just one at a time. The booking page allows for this as you can see here -

Booking page view

However on my Stripe dashboard only one payment has been taken for one space -

Stripe payment

How do I solve this so it takes the full payment indicated on the booking view?

Here's my Controller and view code -

bookings_controller.rb

class BookingsController < ApplicationController        before_action :authenticate_user!        def new          # booking form          # I need to find the event that we're making a booking on          @event = Event.find(params[:event_id])          # and because the event "has_many :bookings"          @booking = @event.bookings.new(quantity: params[:quantity])          # which person is booking the event?          @booking.user = current_user          #@booking.quantity = @booking.quantity          @total_amount = @booking.quantity.to_f * @event.price.to_f          end              def create          # actually process the booking          @event = Event.find(params[:event_id])          @booking = @event.bookings.new(booking_params)          @booking.user = current_user            Booking.transaction do                @event.reload              if @event.bookings.count > @event.number_of_spaces              flash[:warning] = "Sorry, this event is fully booked."              raise ActiveRecord::Rollback, "event is fully booked"              end           end                  if @booking.save                # CHARGE THE USER WHO'S BOOKED              # #{} == puts a variable into a string              Stripe::Charge.create(amount: @event.price_pennies, currency: "gbp",                  card: @booking.stripe_token, description: "Booking number #{@booking.id}")                flash[:success] = "Your place on our event has been booked"              redirect_to event_path(@event)          else              flash[:error] = "Payment unsuccessful"              render "new"          end            if @event.is_free?                @booking.save!              flash[:success] = "Your place on our event has been booked"              redirect_to event_path(@event)          end      end          private        def booking_params          params.require(:booking).permit(:stripe_token, :quantity)      end        end  

booking.new.html.erb

<div class="col-md-6 col-md-offset-3" id="eventshow">    <div class="row">      <div class="panel panel-default">          <div class="panel-heading">              <h2>Confirm Your Booking</h2>          </div>                    <div class="calculate-total">                                <p>                                    Confirm number of spaces you wish to book here:                                      <input type="number" placeholder="1"  min="1" value="1" class="num-spaces">                                </p>                                  <p>                                      Total Amount                                      £<span class="total" data-unit-cost="<%= @event.price %>">0</span>                                  </p>                            </div>                            <%= simple_form_for [@event, @booking], id: "new_booking" do |form| %>                         <span class="payment-errors"></span>                    <div class="form-row">                      <label>                        <span>Card Number</span>                        <input type="text" size="20" data-stripe="number"/>                      </label>                  </div>                    <div class="form-row">                    <label>                    <span>CVC</span>                    <input type="text" size="4" data-stripe="cvc"/>                    </label>                  </div>                    <div class="form-row">                      <label>                          <span>Expiration (MM/YYYY)</span>                          <input type="text" size="2" data-stripe="exp-month"/>                      </label>                      <span> / </span>                      <input type="text" size="4" data-stripe="exp-year"/>                  </div>              </div>              <div class="panel-footer">                       <%= form.button :submit %>                  </div>     <% end %>  <% end %>          </div>    </div>  </div>      <script type="text/javascript">      $('.calculate-total input').on('keyup', calculateBookingPrice);    function calculateBookingPrice() {    var unitCost = parseFloat($('.calculate-total .total').data('unit-cost')),        numSpaces = parseInt($('.calculate-total .num-spaces').val()),        total = (numSpaces * unitCost).toFixed(2);      if (isNaN(total)) {      total = 0;    }      $('.calculate-total span.total').text(total);  }      $(document).ready(calculateBookingPrice)    </script>        <script type="text/javascript" src="https://js.stripe.com/v2/"></script>    <script type="text/javascript">    Stripe.setPublishableKey('<%= STRIPE_PUBLIC_KEY %>');    var stripeResponseHandler = function(status, response) {      var $form = $('#new_booking');        if (response.error) {      // Show the errors on the form      $form.find('.payment-errors').text(response.error.message);      $form.find('input[type=submit]').prop('disabled', false);      } else {      // token contains id, last4, and card type      var token = response.id;      // Insert the token into the form so it gets submitted to the server      $form.append($('<input type="hidden" name="booking[stripe_token]"     />').val(token));      // and submit      $form.get(0).submit();      }    };      // jQuery(function($)  { - changed to the line below    $(document).on("ready page:load", function () {        $('#new_booking').submit(function(event) {        var $form = $(this);          // Disable the submit button to prevent repeated clicks        $form.find('input[type=submit]').prop('disabled', true);          Stripe.card.createToken($form, stripeResponseHandler);          // Prevent the form from submitting with the default action        return false;      });    });  </script>  

Do I need to add 'price' to my booking_params? I already have 'quantity' in there?

Do I need to add a 'total_amount' column to my bookings table? Or is it related to my Stripe action in the controller and the amount?

Any help is appreciated.

When fetching data using an api, is it best to store that data on another database, or is it best to keep fetching that data whenever you need it? [duplicate]

Posted: 09 Sep 2016 04:50 AM PDT

This question already has an answer here:

I'm using the TMDB api in order to fetch information such as film titles and release years, but am wondering whether I need to create an extra database in order to store all this information locally, rather than keep having to use the api to get the info? For example, should I create a film model and call:

film.title  

and by doing so accessing a local database with the title stored on it, or do I call:

Tmdb::Movie.detail(550).title  

and by doing so making another call to the api?

Style Popover Bootstrap

Posted: 09 Sep 2016 04:25 AM PDT

This is how I'm showing popover in my app -

%span{:tabindex => "0", "data-content" => "#{render 'description', logs_arr: log_msg(task, date)}", "data-container" => "body", "data-toggle" => "popover", :title => "#{task.name}"  

JS -

$(function () {          $('[data-toggle="popover"]').popover({ trigger: 'hover', html : true, placement: 'auto right', animation: false})  {);  

I cannot use .popover-content class in css as it is already used somewhere else in app, can anyone suggest me another way of styling the popover.

How to get friends list with the new facebook Api v2.7 [duplicate]

Posted: 09 Sep 2016 04:04 AM PDT

I am using Ruby on Rails framework, I have write this code to get the Facebook friends list, But its showing blank array.

uri = URI('https://graph.facebook.com/me/friends')    params = { access_token: 'xxxxxxxEAAOWo2ozdncBAExxxxxxxxx',fields: 'id,name' }    uri.query = URI.encode_www_form(params)  res = Net::HTTP.get_response(uri)  if res.is_a?(Net::HTTPSuccess)    JSON.parse(res.body)  else    nil  end    Output is:   {    "data": [    ],    "summary": {      "total_count": xxxx    }  }  

Remove am enqueued job from sidekiq

Posted: 09 Sep 2016 03:52 AM PDT

I am using sidekiq gem to run tasks in the background.

job_id = BulkUploadWorker.perform_async(params)      session[:job_id] =  job_id  

Now in my different method I have done something like this

queue = Sidekiq::Queue.new        ap queue        queue.each do |job|          ap job          # using jid          job.delete if job.jid == session[:job_id]        end  

but the issue is that the ap queue is not printing anything. Any idea?

Ruby on Rails - different jQuery results in development and production for adblock message

Posted: 09 Sep 2016 04:32 AM PDT

In my application I added some jQuery codes to show a message when user has adblock on. In my development ENV I can see the message, but with same code in production ENV it doesn't work/do the same thing.

Here is my code

var canRunAds = true;    function hallo(){      $("#showmsg").html("<p>You are using adblock</p>");    }    if( window.canRunAds === undefined ){      hallo();    }  

I even created a file called showads.js and included it to my head with var canRunAds = true; but in production it changes to var canRunAds != 0; for reasons.

How can I get it to work or is it something I do wrong?

No comments:

Post a Comment