Thursday, December 8, 2016

Getting "Error during processing: (ArgumentError) invalid byte sequence in UTF-8" when checking "valid?" method from my model | Fixed issues

Getting "Error during processing: (ArgumentError) invalid byte sequence in UTF-8" when checking "valid?" method from my model | Fixed issues


Getting "Error during processing: (ArgumentError) invalid byte sequence in UTF-8" when checking "valid?" method from my model

Posted: 08 Dec 2016 08:10 AM PST

I'm using Rails 4.2.7 with PostGres 9.5. I'm getting a strange error when I check if my model is valid. I have a name field, defined in my PostGres db as such …

 name              | character varying           |   

However, when I save this value into my model (some things may not cut and paste right from my editor …)

Beth Ordu?±a  

And then I run

      if !insert.valid?  

on a model with the following validation rules

class MyObjectTime < ActiveRecord::Base    belongs_to :my_object    has_one :linked_my_object, class_name: 'MyObject'    belongs_to :state    belongs_to :country      validates :time_in_ms, numericality: { greater_than: 0 }    validates :age, numericality: { greater_than: 0 }, :allow_blank =>      validates :name, presence: true, unless: :first_name_last_name_empty_and_user_id_is_not?      attr_accessor :name_city, :time_str, :hometown, :division, :age_group_rank_str, :gender_rank_str, :overall_rank_str  

I get the error below …

Error during processing: (ArgumentError) invalid byte sequence in UTF-8  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/object/blank.rb:117:in `==='  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/core_ext/object/blank.rb:117:in `blank?'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activemodel-4.2.7.1/lib/active_model/validator.rb:150:in `block in validate'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activemodel-4.2.7.1/lib/active_model/validator.rb:148:in `each'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activemodel-4.2.7.1/lib/active_model/validator.rb:148:in `validate'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/validations/presence.rb:5:in `validate'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:455:in `public_send'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:455:in `block in make_lambda'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:182:in `block in conditional'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:504:in `block in call'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:504:in `each'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:504:in `call'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:92:in `__run_callbacks__'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:778:in `_run_validate_callbacks'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activemodel-4.2.7.1/lib/active_model/validations.rb:399:in `run_validations!'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activemodel-4.2.7.1/lib/active_model/validations/callbacks.rb:113:in `block in run_validations!'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:88:in `__run_callbacks__'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activesupport-4.2.7.1/lib/active_support/callbacks.rb:778:in `_run_validation_callbacks'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activemodel-4.2.7.1/lib/active_model/validations/callbacks.rb:113:in `run_validations!'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activemodel-4.2.7.1/lib/active_model/validations.rb:338:in `valid?'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/validations.rb:58:in `valid?'  /Users/davea/Documents/workspace/myproject/app/services/abstract_import_service.rb:154:in `block (2 levels) in save_my_object_time_results'  /Users/davea/Documents/workspace/myproject/app/services/abstract_import_service.rb:152:in `each'  /Users/davea/Documents/workspace/myproject/app/services/abstract_import_service.rb:152:in `block in save_my_object_time_results'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `block in transaction'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/transaction.rb:184:in `within_new_transaction'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `transaction'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/transactions.rb:220:in `transaction'  /Users/davea/Documents/workspace/myproject/app/services/abstract_import_service.rb:149:in `save_my_object_time_results'  /Users/davea/Documents/workspace/myproject/app/services/abstract_import_service.rb:92:in `process_my_object_data'  /Users/davea/Documents/workspace/myproject/app/services/active_com_my_object_finder_service.rb:119:in `block in process_my_object_link'  /Users/davea/Documents/workspace/myproject/app/services/active_com_my_object_finder_service.rb:109:in `each'  /Users/davea/Documents/workspace/myproject/app/services/active_com_my_object_finder_service.rb:109:in `process_my_object_link'  /Users/davea/Documents/workspace/myproject/app/services/abstract_my_object_finder_service.rb:29:in `block in process_data'  /Users/davea/Documents/workspace/myproject/app/services/abstract_my_object_finder_service.rb:28:in `each'  /Users/davea/Documents/workspace/myproject/app/services/abstract_my_object_finder_service.rb:28:in `process_data'  /Users/davea/Documents/workspace/myproject/app/services/run_crawlers_service.rb:18:in `block in run_all_crawlers'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/relation/delegation.rb:46:in `each'  /Users/davea/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.7.1/lib/active_record/relation/delegation.rb:46:in `each'  /Users/davea/Documents/workspace/myproject/app/services/run_crawlers_service.rb:5:in `run_all_crawlers'  

How do I avoid this error without changing the content of the string? If PostGres is able to save this data, that's the only thing I care about. I do not know in advance what type of encoding the value of "name" will be when I write to it. I can modify the PostGres column data type if necessary.

links with 'data-disable-with' are still disabled after pressing the back button on rails 5 (turbolinks & jquery ujs)

Posted: 08 Dec 2016 08:03 AM PST

So I have a simple link:

%td= link_to("#{fa("institution")} #{entity.short_name}".html_safe, entity_path(entity), class: "button", data: {disable_with: "<i class=\"fa fa-spin fa-circle-o-notch\"></i>".html_safe})

When I press this link it shows a spinning icon and it redirects me to an other page. When I press the back button it still displays the spinning icon.

So I tried to fix this with multiple workarounds:

  • I read this issue and added autocomplete: "off" to the link but it does not work.
  • I found this question on SO, discovered the $.rails.enableElement() function and tried on my browser console:
  • $.rails.enableElement($("a"))
  • $.rails.enableElement($('[data-disable-with]'))

That doesn't work either. Do you have any idea why any of these solutions isn't working? any suggestion?

Ho do I separate modules into separate files in Rails

Posted: 08 Dec 2016 07:57 AM PST

I have an adapter module in my app that is kind of long, so I want to separate it into separate files. I found two references that give a possible solution:

How to split a module over multiple files in Rails?

Breaking ruby module across several files

Essentially what these say is to organize the code in the following structure:

Adapters -adapter.rb adapters --foo.rb --bar.rb

This is my code so far

adapters/adapter.rb

  require_relative './adapter/foo'    require_relative './adapter/bar'  module Adapter   #have also tried with the require_relatives in here and without them at all     end  

adapters/adapter/foo.rb

module Adapter   class Foo     def self.method1     end   end   end  

adapters/adapter/bar.rb

module Adapter   class Bar     def self.other_method     end   end   end  

The issue is that it works sometimes and other times I get a NameError: uninitialized constant Adapter::Foo

It usually works when I first start the server with rails s, but then it doesn't if I navigate to the route that calls this with from a different page.

Any thoughts?

How do I create a schema for a blog where posts belong to categories (e.g. Music, Anime, Products) & relate to different tables based on category?

Posted: 08 Dec 2016 07:54 AM PST

I'm working on a Rails app and have made some initial migrations and associations. Here's the schema I currently have:

Current Schema

Right now, I'm not sure if this schema will actually work. I'm trying to include different data in my posts depending on the category (e.g. If the post is in the "Music" category, it will show the title of the record, along with the artists who created it). The way I have it now, some of the tables will have a hardcoded category_id (e.g. products, episodes, records).

Testing child model with RSPEC and getting the error undefined method id

Posted: 08 Dec 2016 07:58 AM PST

I have two model classes in a "parent-chid" relationship, or association.

organizations is the parent table / model having the attributes: id, organization_name, created_at and updated_at.

events is the child table / model having the attributes: id, event_description, host_name, created_at, updated_at and organization_id.

The association between organizations and events records is events.organization_id = organizations.id, or as is specified in the model classes:

class Event < ApplicationRecord  ...    belongs_to :organization  ...  end    class Organization < ApplicationRecord  ...    has_many  :events, :dependent => :destroy  ...  end  

The tests for organizations model and organizations controller runs without any errors. The test for events controller is not build yet. The app fully functional and is working without any errors.

The problem I have is that I cannot make the Events model test to pass.

Here is my code.

factories/organizations

FactoryGirl.define do    factory :organization do      organization_name { Faker::Company.name }    end    factory :invalid_organization, class: Organization do      organization_name ''    end  end  

factories/events

FactoryGirl.define do    factory :event do      event_description { Faker::Lorem.sentence(3) }      host_name { Faker::Internet.domain_name }      organization = build(:organization)      organization_id = organization.id    end  end  

I am trying to create an organization first and use the id for the organization_id attribute of the new event to be created.

And this is the file event_spec.rb

require 'rails_helper'    RSpec.describe Event, type: :model do    it "has a valid factory" do      event = build(:event)      expect(event).to be_valid    end    it { is_expected.to validate_presence_of(:event_description) }    it { is_expected.to validate_presence_of(:host_name) }    it { is_expected.to validate_presence_of(:organization_id) }    it { is_expected.to belong_to(:organization) }  end  

Basically I want to create first an organization and use this id to be assigned to organization_id when I am creating and event.

When running the test rspec spec/models/event_spec.rb I am getting this error:

/Users/levi/ror/events-handler/spec/factories/events.rb:6:in `block (2 levels) in <top (required)>': undefined method `id' for #<FactoryGirl::Declaration::Static:0x007febc03db798> (NoMethodError)  

Don't know how to fix it or how to write a better test?

Not displaying a column header when there is no data in that column

Posted: 08 Dec 2016 08:02 AM PST

I have the following code:

%table.table-base.table-striped#provider-payments-for-claim    %thead      %tr        %th= t('provider_payments.check_date')        %th= t('provider_payments.denial')    %tbody      - @provider_payments.each do |provider_payment|        %tr{:id=>"provider-payment-#{provider_payment.id}"}         %td= provider_payment.check_number          %td= provider_payment.denial_reason.nil? ? '': provider_payment.denial_reason  

It is correctly displaying provider_payment.denial_reason only if it is not null. The problem is, it's always displaying the column header:

%th= t('provider_payments.denial')  

is there some way that I can not display this when all instances of provider_payment.denial_reason are nil?

NameError in RailsAdmin::Main#index

Posted: 08 Dec 2016 07:29 AM PST

I'm using rails_admin along with the devise gem, looks like everything is working fine with dashboard but whenever I switch to user it throw uninitialized constant User::Authentication raise NameError. new("uninitialized constant #{candidates.first}", candidates.first) error. https://i.stack.imgur.com/DWOP4.png This is my error screenshot. Any help will be appreciated. Below is my user.rb file,

class User < ApplicationRecord   # Include default devise modules. Others available are:   # :confirmable, :lockable, :timeoutable and :omniauthable   devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable     has_many :posts   has_many :comments   has_many :authentications  end  

Why is this attribute lost before it's evaluated in this rspec test?

Posted: 08 Dec 2016 07:27 AM PST

I am using devise and have overridden the registrations controller to allow a user to be "soft-deleted" following the instructions here: devise/wiki/How-to:-Soft-delete-a-user.

I've put some puts commands through my code to follow the test and my rspec result looks like this:

    10:00:30 - INFO - Running: spec/controllers/users/registrations_controller_spec.rb      ..  >   BEFORE: id:2, deleted_at:  >    -- model: id:2, deleted_at:2016-12-08 15:00:35 UTC  >    -- controller: id:2, deleted_at:2016-12-08 15:00:35 UTC  >   AFTER: id:2, deleted_at:      F..        Failures:          1) Users::RegistrationsController GET #destroy sets 'deleted_at' date for user           Failure/Error: expect(user.deleted_at).to_not be_nil               expected: not nil                  got: nil           # ./spec/controllers/users/registrations_controller_spec.rb:44:in `block (3 levels) in <top (required)>'        Finished in 0.37438 seconds (files took 3.7 seconds to load)      5 examples, 1 failure  

As the puts show, my user starts out with the deleted_at field set to null. The model sets deleted_at to the current time and the controller confirms that the date is set, but by the time I get to my expect() statement in my test user.deleted_at is back to nil. This appears to be a problem with my test because the application functions properly.

/spec/controllers/users/registrations_controller_spec.rb

  require 'rails_helper'    require 'factory_girl_rails'      RSpec.describe Users::RegistrationsController, type: :controller do           include Devise::Test::ControllerHelpers         describe "GET #destroy" do            it "sets 'deleted_at' date for user" do            request.env["devise.mapping"] = Devise.mappings[:user]              # sign-in user            user = FactoryGirl.create(:user_for_account_update)            sign_in(user, scope: :user) # note: does not verify correct password              # soft-delete user            puts "BEFORE: id:#{user.id}, deleted_at:#{user.deleted_at}"            delete :destroy, {:id => user.id}            puts "AFTER: id:#{user.id}, deleted_at:#{user.deleted_at}"              expect(user.deleted_at).to_not be_nil          end       end    end  

/spec/factories/user.rb

require 'ffaker'    FactoryGirl.define do    factory :user do |u|      @pass = "password"        name FFaker::Name.name      email { |me| "#{name.to_s.gsub(/\s/,'.')}_#{rand(1000).to_s}@testing.com" }      password @pass        factory :user_for_account_update do        password_confirmation @pass        confirmed_at Date.today      end    end  end  

/app/models/user.rb

  ...      # instead of deleting, indicate the user requested a delete & timestamp it    def soft_delete      update_attribute(:deleted_at, Time.current)      puts " -- model: id:#{id}, deleted_at:#{deleted_at.to_s}"    end      ...  

/app/controllers/users/registrations_controller.rb

# This class overrides devise's registration controller.  All  # other devise actions remain (I believe) handled as usual by   # devise.  I think it is the route that does that by specifying  # this controller specifically for the purpose of registrations  #  # see also: http://stackoverflow.com/questions/3546289  class Users::RegistrationsController < Devise::RegistrationsController    before_filter :configure_permitted_parameters, if: :devise_controller?      # SOFT DELETE /resource    # Follows devise guide: https://github.com/plataformatec/devise/wiki/How-to:-Soft-delete-a-user-when-user-deletes-account    def destroy      resource.soft_delete      Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)      set_flash_message :notice, :destroyed if is_flashing_format?      yield resource if block_given?      respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }      puts " -- controller: id:#{resource.id}, deleted_at:#{resource.deleted_at}"    end      protected      # we have to explicitly permit params in overridden controllers like this    # see https://github.com/plataformatec/devise#strong-parameters    def configure_permitted_parameters      devise_parameter_sanitizer.permit(:sign_up) do |u|        u.permit(:name, :email, :password, :password_confirmation)      end      devise_parameter_sanitizer.permit(:account_update) do |u|        u.permit(:name, :email, :password, :password_confirmation, :current_password)      end    end  end  

How to pass validation errors ActiveAdmin

Posted: 08 Dec 2016 07:48 AM PST

I have a custom controller (I'm using it as a patch for issue ActiveAdmin not saving has_many nested object)

the problem I need to fix is the validation errors and keeping the form data. Before I did the custom controller, the errors would pop up underneath the input field like so

Screnshot

but now they do not show up. Please help! Thanks :)

ActiveAdmin.register

controller do      def create          @section = AbqCouncilors::Councilor.create!(permitted_params[:abq_councilors_councilor].as_json)          redirect_to admin_faq_sections_path, notice: "Section was successfully created!"              end  end  

Postgres server shutdown from simple select all on a small dataset from ActiveRecord query

Posted: 08 Dec 2016 07:19 AM PST

I have the following endpoint in my rails app:

def index   if params.key?(:start)         if params[:start].to_i.to_s == params[:start] #unix epoche time format               p = Param                      .where(devise_id: params[:devise_id])                      .where('"TimeStamp" >= ?', Time.at(params[:start].to_i))                      .order('created_at DESC')        else            raise Exceptions::RequestError, '...'        end  end  

So far so good. The params table has around 20000 entries for the desired devise_id. But one api call to return all 20000 entries postgres got shutdown with the following error message:

2016-12-08 12:22:58 CET LOG:  server process (PID 16510) was terminated by signal 9: Killed  2016-12-08 12:22:58 CET DETAIL:  Failed process was running: SELECT   COUNT(*) FROM "params" WHERE "params"."devise_id" = $1  2016-12-08 12:22:58 CET LOG:  terminating any other active server processes  

I could not reproduce this postgresql crash.

However unicorn is setup to timeout after 30 seconds. Testing this endpoint , sometimes the response takes slightly longer, so the unicorn worker is killed and another one is started by the unicorn master. (I did not think about this in the design, implementation phase and i am going to change that soon to some partitioning) The database access takes some milliseconds but formatting all data in a ruby hash takes most of the time.

I would like now to understand why the postgresql server crashed and how prevent this. 20000 entries is almost nothing for psql. This only appeared once but i would like to keep it that way ;)

Stack:

  • psql (PostgreSQL) 9.3.13
  • unicorn 5.1.0
  • Rails 4.2.7
  • Ruby 2.3.0

PostgeSQL in Amazon EC2

Posted: 08 Dec 2016 07:07 AM PST

I try to set up Amazon EC2 with Vagrant and Chef-zero. Chef contains only one receipt for the installation of Nginx, Ruby, PostgreSQL, that is those utilities that are necessary for a Ruby on Rails stack. For PostgreSQL installation I use this cookbook https://supermarket.chef.io/cookbooks/postgresql. It automatically adds "local all all peer" to the end of pg_hba.conf. If I run Chef on my local machine in VirtualBox, everything is OK. But if I run it on Amazon, PostgreSQL gives an error "invalid authentication method "peer". What is the reason? Maybe, I should use Amazon RDS instead of running the Ruby stack and PostgreSQL on the same machine? Locally, I use Centos 7.2, but on Amazon EC2 - Amazon Linux AMI 2016.09.0.

/var/lib/pgsql/9.2/data/pg_hba.conf

# This file was automatically generated and dropped off by Chef!    # PostgreSQL Client Authentication Configuration File  # ===================================================  #  # Refer to the "Client Authentication" section in the PostgreSQL  # documentation for a complete description of this file.    # TYPE  DATABASE        USER            ADDRESS                 METHOD    ###########  # Other authentication configurations taken from chef node defaults:  ###########    local   all             postgres                                ident    local   all             all                                     ident    host    all             all             127.0.0.1/32            md5    host    all             all             ::1/128                 md5    # "local" is for Unix domain socket connections only  local   all             all                                     peer  

logfile:

LOG:  invalid authentication method "peer"  CONTEXT:  line 24 of configuration file "/var/lib/pgsql/9.2/data/pg_hba.conf"  FATAL:  could not load pg_hba.conf  

Rails 5 edit multiple not showing values in table

Posted: 08 Dec 2016 07:04 AM PST

I am creating multiple edit on my app. I have followed the revised Rails screencast and this code that adapts it to Rails 5.

In my Categories Controller:

def edit_multiple      @categories = Category.where(ID: params[:category_ids])      redirect_to categories_url  end  

In my index:

   <table class="table" summary="Category list">         <tr class="header">         <th style="text-align: left"><%= sort_link(@q, :NAME, 'NAME', default_order: :desc) %></th>         <th style="text-align: left">POSITION</th>         <th style="text-align: left">ACTIONS</th>        </tr>          <%= render "list" %>     </table>       <%= submit_tag "Edit Checked" %>  

In my list partial:

<% form_tag edit_multiple_categories_path, method: :get do %>          <% @categories.each do |category| %>        <tr class="<%= cycle('odd', 'even') %>">          <td><%= check_box_tag "category_ids[]", category.ID %></td>          <td><%=  link_to category.NAME, {:action => 'show', :ID => category.ID} %>          <td><%= category.RANK_POSITION %></td>          <td class="actions">            <%= link_to("Edit", {:action => 'edit', :ID => category.ID}, :class => 'button tiny') %>            <%= link_to("Delete", {:action => 'delete', :ID => category.ID}, :class => 'alert button tiny') %>          </td>        </tr>        <% end %>        <% end %>  

When I open the categories page, it doesn't show anything from _list partial. There's only table headers and Edit Checked button.

Before adding the code relative to multiple edits the table was showing values from partial.

Note that db column names are capital as I'm building the app on existing db.

How can I fix it?

Active Model Serializer not responding with the correct attributes

Posted: 08 Dec 2016 07:43 AM PST

I am working on a rails-api project where I am using active model serialiazer. But unfortunately its not working as expected. This is my V1::HuntsController

class V1::HuntsController < V1::MainController    def index      render json: Hunt.all    end  end  

My hunts serializer looks like this

class HuntSerializer < ActiveModel::Serializer    belongs_to :user    attributes :id,:title,:picture_url,:clue    private    def picture_url      object.picture.url    end  end  

But in my response i am getting all the attributes from hunt. I tried to explicitly define serializer to avoid versioning issues as well.

render json: {data: Hunt.all } ,each_serializer: HuntSerializer  

But nothing seems to work. In the logs I can see,

[active_model_serializers] Rendered V1::HuntSerializer with Hash (32.36ms)  

Whats happening here. Any help would be appreciated.

How can I return a subclass from a FactoryGirl factory?

Posted: 08 Dec 2016 08:12 AM PST

I have Fruits that can either be Apples or Oranges. I never want to actually instantiate the Fruit class. I can define subclasses in factories like this:

# factories.rb  factory :fruit do    juiciness 3    ripeness 4      factory :apple, class: Apple do      color 'red'    end      factory :orange, class: Orange do      color 'orange'    end  end  

I want FactoryGirl.create_list :fruit, 10 to return a list of Apple and Orange objects, not Fruit objects. How can I get FactoryGirl to return randomly an Apple or an Orange when I call FactoryGirl.create :fruit?

Rails: Getting timestamp when user visits "new" page (and save it into the database)

Posted: 08 Dec 2016 07:07 AM PST

I want to save the timestamp when a user visits the posts#new page (.../posts/new) for the first time and save this timestamp in the posts table in the database.

What I've done so far

  1. In the posts table, I've added and migrated a column named first_time_visit which has the datatype timestamp
  2. In my posts_controller.rb I've initialised a @post with the first_time_visit attribute set to Time.now
  3. I have already whitelisted the "first_time_visit" attribute.

Problem:

  • After creating and saving a new post, the first_time_visit column is still "nil".

In my posts_controller.rb

def new     @post = Post.new(first_time_visit: Time.now)  end    def create    @post = current_user.posts.build(post_params)      if @post.save      redirect_to posts_path, notice: "Post saved."    else      render 'new', notice: "Post could not be saved."    end  end    ...    private  def post_params    params.require(:post).permit(:description, :link, :first_time_visit)  end   

I've also tried another solution:

In my post.rb model:

def add_first_time_visit(time)    self.first_time_visit = time  end  

In my posts_controller.rb:

def new     @post = Post.new    @post.add_first_time_visit(Time.now)  end  

But this solution also only gives me a "nil".

Foundation flash message not displaying properly in Rails

Posted: 08 Dec 2016 05:55 AM PST

In my controller I have...

...      flash[:info] = "Successfully Created Webinar"          redirect_to requests_path      end  

In my layout I have...

...      <% flash.each do |name, msg| %>          <% if msg.is_a?(String) %>            <%= content_tag :div, msg, class: "alert-box #{name} radius" %>          <% end %>        <% end %>      <%= yield %>  ...  

When my controller action runs I see the text from the flash message, but there is no sytle associated with it. Based on the Foundation Doc the html should look like this...

<div data-alert class="alert-box success radius">    This is a success alert with a radius.    <a href="#" class="close">&times;</a>  </div>  

However, mine looks like...

<div class="alert-box info radius">Successfully Created Request</div>  

...so it looks like I am not getting the data-alert name set for the div?

Any help appreciated.

Connection Timed out. Please suggest us regarding the configuration

Posted: 08 Dec 2016 05:55 AM PST

We are using heroku redistogo lite plan

which has

````  # = Limits ===================================================================  maxmemory 52428800  maxmemory-policy volatile-lru  maxmemory-samples 3    maxclients 128  timeout 150    `````  

in procfile

```  worker: bundle exec sidekiq -c 3 -v -q default -q medium    ```  

My configuration:

```  require 'sidekiq'  require 'sidekiq/web'  require 'log4r'    Sidekiq.configure_server do |config|  Sidekiq::Logging.logger = Log4r::Logger.new 'sidekiq'  Sidekiq::Logging.logger.level = Log4r::INFO  Sidekiq::Logging.logger.level = Logger::WARN  Rails.logger = Sidekiq::Logging.logger    # config.redis = { db: 1 }    config.redis = { url: ENV['REDISTOGO_URL'] }    config.server_middleware do |chain|      chain.add Sidekiq::Status::ServerMiddleware, expiration: 90.minutes # default    end  end    Sidekiq.configure_client do |config|    config.redis = { size: 1, url: ENV['REDISTOGO_URL'] }    config.client_middleware do |chain|      chain.add Sidekiq::Status::ClientMiddleware, expiration: 90.minutes # default    end  end    # ActiveRecord::Base.logger = Sidekiq::Logging.logger  Sidekiq::Web.set :session_secret, Rails.application.secrets[:secret_token]  Sidekiq::Web.set :sessions, Rails.application.config.session_options    `````  

Error:

`````  Error message  Errno::ETIMEDOUT: Connection timed out    Stack trace (show Rails)  …by/2.2.0/gems/redis-3.3.2/lib/redis/connection/  ruby.rb: 105:in `write_nonblock'  …by/2.2.0/gems/redis-3.3.2/lib/redis/connection/  ruby.rb: 105:in `_write_to_socket'  …by/2.2.0/gems/redis-3.3.2/lib/redis/connection/  ruby.rb: 131:in `block in write'  …by/2.2.0/gems/redis-3.3.2/lib/redis/connection/  ruby.rb: 130:in `loop'  …by/2.2.0/gems/redis-3.3.2/lib/redis/connection/  ruby.rb: 130:in `write'  …by/2.2.0/gems/redis-3.3.2/lib/redis/connection/  ruby.rb: 374:in `write'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 271:in `block in write'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 250:in `io'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 269:in `write'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 228:in `block (3 levels) in process'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 222:in `each'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 222:in `block (2 levels) in process'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 367:in `ensure_connected'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 221:in `block in process'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 306:in `logging'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 220:in `process'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 187:in `call_pipelined'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 157:in `block in call_pipeline'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 293:in `with_reconnect'  …bundle/ruby/2.2.0/gems/redis-3.3.2/lib/redis/  client.rb: 155:in `call_pipeline'  …vendor/bundle/ruby/2.2.0/gems/redis-3.3.2/lib/  redis.rb:2304:in `block in multi'  …vendor/bundle/ruby/2.2.0/gems/redis-3.3.2/lib/  redis.rb:  58:in `block in synchronize'         /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/  monitor.rb: 211:in `mon_synchronize'  …vendor/bundle/ruby/2.2.0/gems/redis-3.3.2/lib/  redis.rb:  58:in `synchronize'  …vendor/bundle/ruby/2.2.0/gems/redis-3.3.2/lib/  redis.rb:2296:in `multi'  …ems/sidekiq-status-0.6.0/lib/sidekiq-status/  storage.rb:  16:in `block in store_for_id'  …ems/sidekiq-status-0.6.0/lib/sidekiq-status/  storage.rb: 102:in `block in redis_connection'  ….2.0/gems/connection_pool-2.2.1/lib/  connection_pool.rb:  64:in `block (2 levels) in with'  ….2.0/gems/connection_pool-2.2.1/lib/  connection_pool.rb:  63:in `handle_interrupt'  ….2.0/gems/connection_pool-2.2.1/lib/  connection_pool.rb:  63:in `block in with'  ….2.0/gems/connection_pool-2.2.1/lib/  connection_pool.rb:  60:in `handle_interrupt'  ….2.0/gems/connection_pool-2.2.1/lib/  connection_pool.rb:  60:in `with'  …ems/sidekiq-status-0.6.0/lib/sidekiq-status/  storage.rb: 101:in `redis_connection'  …ems/sidekiq-status-0.6.0/lib/sidekiq-status/  storage.rb:  15:in `store_for_id'  …q-status-0.6.0/lib/sidekiq-status/  client_middleware.rb:  26:in `call'  …2.0/gems/sidekiq-4.1.4/lib/sidekiq/middleware/  chain.rb: 130:in `block in invoke'  …2.0/gems/sidekiq-4.1.4/lib/sidekiq/middleware/  chain.rb: 133:in `call'  …2.0/gems/sidekiq-4.1.4/lib/sidekiq/middleware/  chain.rb: 133:in `invoke'  …le/ruby/2.2.0/gems/sidekiq-4.1.4/lib/sidekiq/  client.rb: 206:in `process_single'  …le/ruby/2.2.0/gems/sidekiq-4.1.4/lib/sidekiq/  client.rb:  65:in `push'  …le/ruby/2.2.0/gems/sidekiq-4.1.4/lib/sidekiq/  worker.rb: 116:in `client_push'  …le/ruby/2.2.0/gems/sidekiq-4.1.4/lib/sidekiq/  worker.rb:  60:in `perform_async'  

Please suggest us.

Ruby version: 2.2.1 Sidekiq / Pro / Enterprise version(s): 4.1.4

If relevant, please include your initializer and any error message with the full backtrace.

Using token based authorization in bootstrap-table

Posted: 08 Dec 2016 05:54 AM PST

I am unable to get token based authorization work with the ajax call in the bootsratp-table under rails. Here is my code:

<table id="reports" data-toggle="table" data-search="true" data-pagination="true" data-side-pagination="server" data-url="../api/v1/projects/1/reports" data-ajax-options='{headers: { "Authorization": "Token token=a3b9ac2c445cced1f9752a45dce768a4"}}' > <thead> ... </thead> </table>

Authorization fails and checking the request headers (both client side with Chrome developer tools and server side), the Token is not included in the header.

What am I missing?

Thanks, Manuel.

how best to compress aws images

Posted: 08 Dec 2016 05:47 AM PST

When I check my home page with google page speed test I get notice to compress my images: Compressing https://d1bng4142lcup0.cloudfront.net/…5c0-9e29-42af-ba42-b0ae59ef2809horse.JPG could save 51KiB (55% reduction).

I have rails 4.2 on heroku using jquery file uploader and aws-sdk to upload to s3 via js. I then serve s3 image files via cloudfront.

In the js uploader I set the quality to .75 and size to around 500 px wide. I serve one file to all devices (bootstrap responsive class displays it nicely). I used this technique to upload https://devcenter.heroku.com/articles/direct-to-s3-image-uploads-in-rails which uses https://github.com/blueimp/jQuery-File-Upload

I have gzip = true in my production.rb and I have compression turned on on cloudfront.

When looking at chrome developer tool under networking I see many things are content-encoding = gzip such as js files, but my png and jpg are not. They do have content lengths however.

How do I compress my files automatically moving forward speed up my site and satisfy the page speed tool? How do I optimize existing images on s3 to be compressed? In other words, do I need to do more during initial upload or can I do some compression on the aws side?

Encryptor.decrypt + unable to decrypt data

Posted: 08 Dec 2016 05:59 AM PST

I have two server with same database on heroku.

below is the data for decryption that working fine on heroku A

salt1 = "\x9F\x80mg\xB1\x9AB~%m\x96\xB9\xADb\xB9'"  key1 =  "\xFF\xA12?\x04\xE4yM\x17\xCD\xB2\x04\xDA(d\xBFp\x85\xDC\xD0\xC8\x86\xC5;\x1C@\va\xD0-\xD3*"  hash1 = "\x10\x13\xD2?\xC1j\xE23\x9A\xB4\x8E\xCD\x05\xA8;M0\xD4|X\xD2z\xAD\xFE"  Encryptor.decrypt(hash1, key: key1, iv: salt1, salt: salt1)  

with help of - Click Here

in Heroku B that have same database. I'm trying to decrypt but can't do. Unable to get why it's not working

I copy and paste above 4 line but it gives me

OpenSSL::Cipher::CipherError: wrong final block length  

PROBLEM 2

When I copy iv from one place to other, It will change

For example - iv = "\xBA\x17\xD9\xFE\xA7\x1A06r`Tx"   

when I copy this to another console it will display like

"\xBA\u0017\xD9\xFE\xA7\u001A06r`Tx"  

I don't understand this.

WHAT I WANT

I want to encrypt data on HEROKU A and decrypt on HEROKU B. How can I do this ?

Error in require 'barby/barcode/code_128' - Rails 2.3.2

Posted: 08 Dec 2016 05:29 AM PST

I have Rails 2.3.2 with ruby 10.04 running in ubuntu 10.04.

What I need is to generate html barcodes using the gem Barby.

According to documentation I have to put this in the controller:

def testbarby    require 'barby'    require 'barby/barcode/code_128'    require 'barby/outputter/html_outputter'    barcode = Barby::Code128B.new('1234')    outputter = Barby::HtmlOutputter.new(barcode)    outputter.to_html  end  

When running I have this :

unmatched (: /(?:\d{2}|Á){2,}/    /usr/local/lib/ruby/gems/1.8/gems/barby-0.6.5/lib/barby/barcode/code_128.rb:409  /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'  /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'  /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'  /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'  /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'  app/controllers/barcode_controller.rb:15:in `testbarby'  -e:1:in `load'  -e:1  

I guess this is something related with encoding.

Thank you for help.

Remove comments when running rspec

Posted: 08 Dec 2016 05:27 AM PST

When I test my rails app using rspec, a bunch of long comments appear. How can I remove them ?

 ActionController::RoutingError:     No route matches [GET] "/events"   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:36:in `call_app'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:24:in `block in call'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/rack/logger.rb:24:in `call'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/method_override.rb:22:in `call'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/runtime.rb:22:in `call'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/sendfile.rb:111:in `call'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:522:in `call'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/urlmap.rb:68:in `block in call'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/urlmap.rb:53:in `each'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-2.0.1/lib/rack/urlmap.rb:53:in `call'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-test-0.6.3/lib/rack/mock_session.rb:30:in `request'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-test-0.6.3/lib/rack/test.rb:244:in `process_request'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/rack-test-0.6.3/lib/rack/test.rb:58:in `get'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/browser.rb:61:in `process'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/browser.rb:36:in `process_and_follow_redirects'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/browser.rb:22:in `visit'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/rack_test/driver.rb:43:in `visit'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/session.rb:233:in `visit'   # /Users/hadi/.rvm/gems/ruby-2.3.0/gems/capybara-2.7.1/lib/capybara/dsl.rb:52:in `block (2 levels) in <module:DSL>'   # ./spec/features/list_movies_spec.rb:5:in `block (2 levels) in <top (required)>'  

Rails: Rolify can not generate user model because one has existed

Posted: 08 Dec 2016 05:39 AM PST

Rails 5.0
Ruby 2.3
Rolify 5.1

I am following rolify's tutorial to do rails g rolify Role User.
But a user model have already existed in my project and it is just an normal user model.
The model to manage users' log in and log out is a model called log_user.
So for now two models have existed user and login_user.
So rails can not generate another user for me. I am not familiar with rolify. Anyone could tell me what I can do to solve this problem?

when I tried rails g rolify Role User, error

/Users/King/.rvm/gems/ruby-2.3.0/gems/thor-0.19.4/lib/‌​thor/actions/inject_‌​into_file.rb:95:in binread': No such file or directory @ rb_sysopen - /Users/...../app/models/user.rb (Errno::ENOENT)

==========================UPDATE=================================
when I tried rails g rolify:role Role User, error shows

kingk-Pro:mypj King$ rails g rolify:role Role User  Running via Spring preloader in process 97622  Expected string default value for '--test-framework'; got false (boolean)  Expected string default value for '--helper'; got true (boolean)  Expected string default value for '--assets'; got true (boolean)  Expected string default value for '--test-framework'; got false (boolean)  Expected string default value for '--test-framework'; got false (boolean)  Expected string default value for '--test-framework'; got false (boolean)  Expected string default value for '--test-framework'; got false (boolean)  Expected string default value for '--test-framework'; got false (boolean)  Expected string default value for '--test-framework'; got false (boolean)  Could not find generator 'rolify:role'. Maybe you meant 'rolify:user', 'rolify' or 'controller'  Run `rails generate --help` for more options.  

Ruby Rails design table

Posted: 08 Dec 2016 08:02 AM PST

I have a model named OrderingRequest I am using state_event_machine gem to record different states,I have states called order_place and order_reject. When I click order_place a dropdown with 3 values should display and also some other values in drop down should display when i select order_reject, my question is how to design this order_place and order_reject data and associate with the my current table.

Rails, where does CarrierWave store files?

Posted: 08 Dec 2016 05:34 AM PST

Couldn't find/understand good documentation on this. I wonder where uploads that are done by CarrierWave goes? As from my understanding it goes directly into the db, right? Could I force it to store (or create like a reference to the file) in my assets pipeline? Today had an issue when couldn't use image_tag since it grabs asset only from the assets pipeline. Could it be that letting users to store files in asset pipeline could be a potentially very risky and harmful?

So my questions:

  • Can I store / reference file in the assets pipeline?

  • Would it be a good idea?

Thanks for sharing!

Nested records using join Rails

Posted: 08 Dec 2016 05:21 AM PST

I have these models

class Car < ApplicationRecord    has_many :car_locations ,:dependent=>:destroy    has_many :rides,:dependent=>:destroy  end    class CarLocation < ApplicationRecord    belongs_to :car  end    class Ride < ApplicationRecord    belongs_to :car  end  

There is a status attribute in Ride Model of boolean type.

Now I want those CarLocations whose car rides status is false or don't have any car ride with in minimum complexity.

Ruby/Rails - Converting an integer into a float excluding existing zeros

Posted: 08 Dec 2016 06:32 AM PST

There must be a simple way to achieve this, I have an DB field containing an integer and I want to reformat it into a float to display.

As an integer my value looks like 6500 and I want it to display as 65.00

Within my model I have attempted to achieve this by creating the following method

def get_payment_amount_as_number    amount = self.payment_amount    return '%.02f' % self.payment_amount.to_f  end  

Which results in the following being displayed: 6500.00

What would the best approach be to either strip the initial zeroes or to simply insert a decimal point?

Whilst I imagine this a ruby related question, I am not sure if rails has a handy helper already in place?

Thank you.

Write text over images on the fly in Rails?

Posted: 08 Dec 2016 05:36 AM PST

The objective is to create a personalized batch like the Stackoverflow batch.

Users may go to the link site.com/batch/username.png, then, they will be provided with a batch with their username and other details over it.

The format (like png) is not strictly important.

Current Approach:

Currently, I have a base image of a batch and aim to place specific text at specific coordinates over the image. The default image is being served but the personalized result is not being achieved. I have tried using ImageMagick and PaperClip gems but no avail.

It will be helpful if someone could provide a sample code snippet to demonstrate this in Ruby on Rails.

Environment:

Our web application is hosted on AWS and uses Rails as a framework.

Thanks.

Prevent users from deleting their email once entered

Posted: 08 Dec 2016 05:06 AM PST

My Rails (using Rails 5) application is currently set up so that users sign-in/sign-up with their mobile number and a password. This was set up using Devise but changing the authentication_keys to mobile_number rather than email.

There is a form where they can add additional details including an email address. Currently there is no validation on e-mail as I do not want it to be mandatory to enter one. However, I would like it so that if the user does choose to enter an e-mail address they are unable to go back and delete it (only update it). There is also this snippet of code in the User model which I thought I could edit to make it require an email when the email field is not blank (but it didn't work):

# app/models/user.rb  def email_required?    false unless email.present?  end  

Error while running the Rails app in Production with nginx and passenger

Posted: 08 Dec 2016 04:04 AM PST

nginx error.log

   /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:475:in `block in eager_load!'     /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:473:in `each'    /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:473:in `eager_load!'    /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:354:in `eager_load!'    /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/application/finisher.rb:59:in `each'    /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/application/finisher.rb:59:in `block in <module:Finisher>'    /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `instance_exec'    /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `run'   /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'   /home/deploy/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'   /home/deploy/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'  /home/deploy/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'    /home/deploy/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'  /home/deploy/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `each'  /home/deploy/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `call'  /home/deploy/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'   /home/deploy/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:226:in  `tsort_each'   /home/deploy/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'   /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:54:in `run_initializers'    /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/application.rb:352:in `initialize!'   /home/deploy/var/www/html/final/config/environment.rb:5:in `<top (required)>'  config.ru:3:in `require_relative'  config.ru:3:in `block in <main>'  /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/rack- 2.0.1/lib/rack/builder.rb:55:in `instance_eval'  /home/deploy/var/www/html/final/vendor/bundle/ruby/2.3.0/gems/rack- 2.0.1/lib/rack/builder.rb:55:in `initialize'   config.ru:1:in `new'  config.ru:1:in `<main>'      /usr/share/passenger/helper-scripts/rack-preloader.rb:110:in `eval'     /usr/share/passenger/helper-scripts/rack-preloader.rb:110:in `preload_app'     /usr/share/passenger/helper-scripts/rack-preloader.rb:156:in `<module:App>'     /usr/share/passenger/helper-scripts/rack-preloader.rb:30:in   `<module:PhusionPassenger>'      /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `<main>'  

I have a rails app in aws ec2 with nginx and passenger .Development environment is working fine but in production there is an issue .

bundle exec rake assets:precompile db:migrate RAILS_ENV=production  

is successful without any error, but while running the application in browser getting the above error.

environment.rb

require_relative 'application'      Rails.application.initialize!  

application.rb

  require_relative 'boot'      require 'rails/all'        Bundler.require(*Rails.groups)      module Final    class Application < Rails::Application       end   end  

Kindly help me with this issue.

No comments:

Post a Comment