Saturday, December 31, 2016

how to display thousands of records | Fixed issues

how to display thousands of records | Fixed issues


how to display thousands of records

Posted: 31 Dec 2016 08:23 AM PST

I have a table called clientes, this table has around 15536 records, which makes data loading extremely slow. How can I optimize the log load to improve the process?

this is my index view

<h1>Clientes</h1>  <style>  .container {  }    </style>            <table id="clientes" class="display"><!--el id clientes es de datatables referenciado en clientes.coffe y display class es una clase de datatables-->    <thead>        <tr><!--active es para sombrear la fila-->        <th>Clave</th>        <th>Nombre</th>        <th>Nombre Corto</th>        <th>Dirección</th>        <th>Colonia</th>        <th>Credito</th>        <th>DiasCredito</th>        <th>LimiteCredito</th>        <th>Saldo</th>        <th>Ruta</th>        <th>Promociones</th>        <th>Acción</th>        <th></th>        </tr>    </thead>      <tbody id="container_clientes">        <%= render @clientes %><!--carga todos los clientes-->  </tbody>  

my partial cliente.html.erb

<tr id="cliente_<%= cliente.id %>">    <td><%=cliente.IdCli%>    </td>    <td><%=cliente.Nombre%></td>    <td><%=cliente.NombreCorto%></td>    <td><%=cliente.Direccion%></td>    <td><%=cliente.Colonia%></td>    <td>      <% if cliente.Credito == true%>        <input type="checkbox" disabled="true" checked="true">      <%else%>        <input type="checkbox" disabled="true" >      <%end%>    </td>    <td><%=cliente.DiasCreedito%></td>    <td><%=cliente.LimiteCredito%></td>    <td>      <% if cliente.detallecob.last != nil%>          <%=cliente.detallecob.last.Saldo%>        <%else%>          <%=cliente.Saldo%>      <%end%>    </td>    <td>      <% if cliente.relclirutas != nil%>        <% cliente.relclirutas.each do |varias| %>          <%=varias.ruta.Ruta%>        <%end%>      <%end%>    </td>    <td>      <% if cliente.relclili != nil%>        <%=cliente.relclili.listapromomast.ListaMaster%>      <%end%>    </td>          <td>          <%= link_to '<i class="fa fa-gift" aria-hidden="true"></i> Activos'.html_safe, activos_cliente_path(cliente), class:"btn btn-primary btn-xs boton" %>            <button type="button" class="btn btn-warning btn-xs" data-toggle="modal" data-target="#myupdatecliente_<%= cliente.id %>">            Editar          </button>          <!--Destroy-->          <% if cliente.Status == true%>            <%= link_to 'Eliminar', cliente, method: :delete, class: "btn btn-danger btn-xs", remote:true %>          <%else%>            <%= link_to 'Habilitar', cliente, method: :delete, class: "btn btn-success btn-xs", remote:true %>          <%end%>        </td>      <td class="no" >      </td>  </tr>  

Rails rollback transaction for bids

Posted: 31 Dec 2016 08:24 AM PST

Hello I'm getting a rollback transaction when I try to create a Bid from the rails console. These are my models:

Product Model

class Product < ApplicationRecord  	belongs_to :user  	belongs_to :category  	has_many :ratings  	has_many :bids    end

Bid model:

class Bid < ApplicationRecord  	belongs_to :products  	belongs_to :user  	  end

User model:

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

And this is my schema:

ActiveRecord::Schema.define(version: 20161231124005) do      create_table "bids", force: :cascade do |t|      t.integer  "amount"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.integer  "user_id"      t.integer  "product_id"      t.index ["product_id"], name: "index_bids_on_product_id"      t.index ["user_id"], name: "index_bids_on_user_id"    end      create_table "categories", force: :cascade do |t|      t.string   "name"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "products", force: :cascade do |t|      t.string   "title"      t.text     "description"      t.string   "image_url"      t.integer  "price"      t.datetime "deadline"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.integer  "user_id"      t.integer  "category_id"    end      create_table "ratings", force: :cascade do |t|      t.integer  "rating"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.integer  "user_id"      t.integer  "product_id"    end      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.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.string   "username"      t.index ["email"], name: "index_users_on_email", unique: true      t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true      t.index ["username"], name: "index_users_on_username", unique: true    end    end

Although I tried to create like so: Bid.create(amount: 500, user_id: 1, product_id:6) it doesn't save because of the rollback transaction.

Thanks in advance

Mysql2::Error: Access denied for user 'rails_user'@'localhost' (using password:YES)

Posted: 31 Dec 2016 07:40 AM PST

I am trying to create a database and connect it with my rails app.

When I try to check if my database are properly connected via:

rails db:schema:dump  

It gives me the ff error:

Mysql2::Error: Access denied for user 'rails_user'@'localhost' (using password:  YES)  bin/rails:4:in `require'  bin/rails:4:in `<main>'  Tasks: TOP => db:schema:dump  (See full trace by running task with --trace)  

This blows my mind as did used the exact password when I created the DB:

default: &default    adapter: mysql2    encoding: utf8    pool: 5    username: rails_user    password: grace0512    host: localhost    development:    <<: *default    database: test_project_development    # Warning: The database defined as "test" will be erased and  # re-generated from your development database when you run "rake".  # Do not set this db to the same as development or production.  test:    <<: *default    database: test_project_test  

I did try this:

grant all on simple_cms_development.* to 'rails_user'@'localhost' identified by '<password>';  flush privileges;  

But did not solve my issue. Any help please?

I really need to solve this to move forward!

AWS::S3::Errors::AccessDenied (Access Denied):

Posted: 31 Dec 2016 07:30 AM PST

I am currently having an issue where I am hosting a rails app on elastic beanstalk and am using S3 to store images. I am using paperclip for this. The problem I am getting is that when I attempt to upload an image I get an error saying 'We're sorry, but something went wrong.' When I checked eb logs. I found that I was getting the error AWS::S3::Errors::AccessDenied (Access Denied): . I've searched online for a couple of hours now and cant seem to find a solution to this issues as Ive set up a IAM account and given the user all the required permission and set permission on the bucket itself. Below is the code I am using.

Paperclip defaults(production.rb)

config.paperclip_defaults = {    :storage => :s3,    :s3_host_name => 's3-eu-west-1.amazonaws.com',    :s3_credentials => {      :bucket => ENV['S3_BUCKET_NAME'],      :access_key_id => ENV['AWS_ACCESS_KEY_ID'],      :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']    }  }  

User.rb

has_attached_file :avatar, styles: { medium: '152x152'},:bucket => 'have bucket here'  

Post.rb

has_attached_file :image, :styles => { :medium => "500px"},:bucket => 'have bucket here'  

If you need any other code please let me know and ill put it in the comments below

Ruby on rails , test is saying a column doesn't exist but its on the schema

Posted: 31 Dec 2016 08:11 AM PST

in my clients table, I have a column named email. But when I made the tests for the clients controller and the model, the tests kept on saying that the clients table has no column named email.

SQLite3::SQLException: table clients has no column named email: CREATE UNIQUE INDEX "index_clients_on_email" ON "clients" ("email")

although I do admit that I didn't initially put that column when I created my table, but I added the column via a separate migration. I ran rake db:migrate and even tried rake db:drop:all, rake db:create:all and then rake db:migrate and it still didn't change anything.

the email column was also added as an index for the clients table.

this is my schema:

ActiveRecord::Schema.define(version: 20161230163248) do      create_table "clients", force: :cascade do |t|      t.string   "name",       null: false      t.text     "email",      null: false      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      add_index "clients", ["email"], name: "index_clients_on_email", unique: true      create_table "projects", force: :cascade do |t|      t.text     "project_description", null: false      t.string   "project_timescale"      t.datetime "created_at",          null: false      t.datetime "updated_at",          null: false      t.integer  "client_id"    end      add_index "projects", ["client_id"], name: "index_projects_on_client_id"    end  

the initial migration for the clients table:

class CreateClients < ActiveRecord::Migration    def change      create_table :clients do |t|        t.string :name, presence: true, null: false        t.timestamps null: false      end    end  end  

migration to add email as an index for the client table:

class AddIndexToClient < ActiveRecord::Migration    def change      add_index:clients, :email, unique: true    end  end  

migration to add the email column:

class AddEmailToClient < ActiveRecord::Migration    def change      add_column :clients, :email, :text    end  end  

the following is my database.yml:

# SQLite version 3.x  #   gem install sqlite3  #  #   Ensure the SQLite 3 gem is defined in your Gemfile  #   gem 'sqlite3'  #  default: &default    adapter: sqlite3    pool: 5    timeout: 5000    development:    <<: *default    database: db/development.sqlite3    # Warning: The database defined as "test" will be erased and  # re-generated from your development database when you run "rake".  # Do not set this db to the same as development or production.  test:    <<: *default    database: db/test.sqlite3    production:    <<: *default    database: db/production.sqlite3  

File to import not found or unreadable: neat/neat

Posted: 31 Dec 2016 06:58 AM PST

I have a Rails project that I'm trying to add Bourbon and Neat to the app. I have installed the gems and I have now tried to include the imports to the main stylesheet. But when I try to refresh the home page I get this error. File to import not found or unreadable: neat/neat. Load paths: it also include this line in the error path <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>

This is my first time trying to add bourbon and neat to a project and I don't really know where to go from here. Any help would be great thanks!

Can't add persons to Rollbar errors in Rails

Posted: 31 Dec 2016 06:52 AM PST

I have defined a current_user method with attr_reader :current_user, but the user is not send to Rollbar. This is my config:

Rollbar.configure do |config| config.access_token = Rails.application.secrets.rollbar_token config.use_sidekiq 'queue' => 'high_priority' end

What is wrong with my config? I have already tried to configurate it with config.person_method = :current_user.

Ruby instance variable and local variable

Posted: 31 Dec 2016 07:02 AM PST

I've always thought instance variable as used only within the definition of a class and can be accessed inside the class. When I am learning rails I am looking at an example like this:

class Movie    def initialize(isbn)      @isbn = isbn    end    def isbn      @isbn    end  end  @movie = Movie.new("0702")  @movie.isbn  

I'm confused that a instance variable appears outside of a class definition. Why use @movie instead of local variable "movie"?

Follow up questions:

  1. Since instance variables can live in a another scope, when the program need to create multiple new objects, do they all have the same name @movie? Are the new object always overwirte the old one?

  2. In a larger program(like a MVC app), does the @movie shared by all the files(model, view, controller)?

How to save measured time in Rails 5?

Posted: 31 Dec 2016 05:53 AM PST

I have a js timer and I need to save the time in format: hour minute second. Like you know Timer.new(hour, minute, sec) (similar). How can i save an interval time in rails db? I just need to know how to save it, i know ho to handle ajax/controller stuff.

Query database starting from a certain id

Posted: 31 Dec 2016 06:35 AM PST

My app's functionality is like Tinder. I will go through the work flow.

  • App loads 10 Hunts (like tinder profiles)
  • User accepts or rejects it
  • Once user accepts or reject, hunt is removed (marked as seen so that it doesnt come back again )
  • When Hunts count become 2 , app loads next 10 hunts. ( This is not second page as seen hunts are already removed )

Here is the tricky part. When it queries database again, the hunt would have the 2 hunts which user hasnt yet accepted or rejected. To avoid duplication I avoid first 2 hunts from the response. But problem occurs if the query is run after one more accept or reject. I would remove 2 hunts expecting normal behavior but this would remove eliminate one hunt which is not a duplicate.

What would a best solution would be to get all the hunts which comes after a certain id.I can use WHERE NOT ID IN by passing the ids. But I would like to know if there is a better solution as I see this would be a pretty common scenario .

I hope I made myself very clear.

The solutions which I have thought of but not really liked

  1. Pass ids of the 2 hunts back and exclude them in the results
  2. Remove duplicates from hunts once I receive response back in my app

All suggestions are welcome. I m using Rails so active record solutions are also welcome.

issue in scrollY in data table

Posted: 31 Dec 2016 04:45 AM PST

I am want to add data table scroll Y feature its working fine but there is a problem of screen resolution . the screen leave more space from the bellow and it leave space from Y axis like bellow images .

enter image description here

my code-

html.erb

   <table class="table table-striped table-hover" id="pendingpodatesort" >   <thead>    <tr>      <th><%= check_box_tag "selectAll", "selectAll" %></th>        <th>Item</th>   <th>Make/Catno</th>   <th>UOM</th>   <th>Qty</th>   <th>Qt_P</th>   <th>Vendor</th>   <th>Phone</th>    <th>No.</th>    <th>Date.</th>    <th>Sort Date</th>    <th>Dlv.Dt</th>    <th>Sort Date</th>    <th>Status</th>    <th>Status Dt</th>    <th>Remarks</th>    <th></th>    <th></th>    <th></th>         </tr>   </thead>      <tbody>      <% @poitems.each do |poitem| %>     <tr>     <% if current_personnel.designation == 4 ||    current_personnel.designation == 5 %>  <td></td>  <% else %>  <td><%= check_box_tag 'poitem[]' , poitem.id %></td>  <% end %>    <td><%= poitem.item.description %></td>    <% if poitem.make_id != nil %>  <td><%= (poitem.make.brand.name)+"/"+(poitem.make.catno) %></td>  <%else %>  <td></td>  <% end%>    <% if poitem.uom_type == nil %>  <td><%= poitem.item.uom.shortform %></td>  <% else %>   <td><%= Uom.find_by_id((Item.find_by_id(poitem.item_id)).dual_uom_id).shortform %></td>  <% end %>    <td><%= poitem.quantity %></td>    <% if poitem.pending_quantity != nil %>  <td><%= poitem.pending_quantity %></td>  <%else%>  <td><%= poitem.quantity %></td>  <%end%>    <td><%= poitem.purchaseorder.vendor.description.titlecase %></td>  <td><%= poitem.purchaseorder.vendor.ref_ph %></td>    <td>PO/<%= poitem.indent.parentindent.warehouse.shortform + "/"+(poitem.purchaseorder.serial.to_s) %></td>       <% @podate=poitem.purchaseorder.date %>    <td><%= @podate.strftime("%d/%m") %></td>     <td><%= @podate.strftime("%m/%d/%y") %></td>    <% @delivery_days=poitem.purchaseorder.delivery_days %>  <% if @delivery_days != nil %>  <td><%= (@podate+(@delivery_days.days)).strftime("%d/%m") %></td>  <td><%= (@podate+(@delivery_days.days)).strftime("%m/%d/%y") %></td>  <% else %>  <td></td>  <td></td>  <% end %>      <% if poitem.purchaseorder.awaiting_pi_payment==true %>    <td>Awaiting for PI Payment</td>    <td></td>    <% elsif poitem.dispatched==true %>    <td>Despatched</td>      <% if poitem.dispatched_date != nil %>      <td><%= poitem.dispatched_date.strftime("%d/%m") %></td>      <% else %>      <td></td>      <% end %>    <% elsif poitem.received_by_transporter==true %>    <td>Received at Transporter Godown</td>        <% if poitem.received_by_transporter_on != nil %>      <td><%= poitem.received_by_transporter_on.strftime("%d/%m") %></td>      <% else %>      <td></td>      <% end %>      <% elsif poitem.delivered_at_plant==true %>    <td>Delivered at Plant</td>      <% if poitem.delivered_at_plant_on != nil %>      <td><%= poitem.delivered_at_plant_on.strftime("%d/%m") %></td>      <% else %>      <td></td>      <% end %>      <% else %>    <td></td>    <td></td>    <% end %>    <% if poitem.dispatch_details==nil %>    <td><%= (poitem.followup_remarks) %></td>    <% elsif poitem.followup_remarks==nil %>    <td><%= (poitem.dispatch_details)%></td>    <% else %>    <td><%= (poitem.dispatch_details)+', '+ (poitem.followup_remarks) %></td>    <% end %>      <% if PoAttachment.where(po_id: poitem.po_id)[0]== nil %>    <td></td>    <% else %>    <td><% PoAttachment.where(po_id: poitem.po_id).each do |attachment| %>    <%= link_to attachment.document.url, class: "btn btn-default btn-xs" do %>    <i class="glyphicon glyphicon-paperclip"></i><% end %>    <% end %></td>    <% end %>        <td> <%= link_to controller: "purchase_order_items", action: "change_status", id: poitem.id, class: "btn btn-default btn-xs" do%>    <i class="glyphicon glyphicon-pencil"></i>    <% end %></td>    <td><%= submit_tag ">", name: poitem.id, :class => 'btn btn-default btn-xs' %></td>       </tr>     <% end %>    </tbody>     </table>    application.js  $(document).ready(function(){   var filterTable=$("#pendingpodatesort").DataTable({   "dom": '<"wrapper"ilt>',   "scrollY":  '510px',   "scrollX":   true,   "lengthMenu": [ [-1, 10, 25, 50, 100], ["All", 10, 25, 50, 100] ],    "aoColumns": [                              {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                            {"iDataSort": 10},                            {"bVisible": false},                            {"iDataSort": 12},                            {"bVisible": false},                            {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                            {"bSortable": true},                                                                                       {"bSortable": true}                           ],       "order": [[ 10, "desc" ]]                               });    $("#filterbox").keyup(function() {        filterTable.search(this.value).draw();      });  });  

How can i adjust this size with out increase zoom on any screen?is there any option to give scroll Y value in %?

I have a video background for my home page,when I open in mobile device instead of video playing,u need to get a image of my choice?

Posted: 31 Dec 2016 02:34 AM PST

What extra attribute should I add so that when opened in mobile or small devices ,image appears instead of video?

I am trying to execute new project in Ruby on rails with new command

Posted: 31 Dec 2016 02:16 AM PST

When I enter the command in windows 7 on my command prompt:

c:\Sites\ Rails new myblog  

The installation gets blocked with the following error:

C:/RailsInstaller/Ruby2.2.0/bin/ruby.exe -r ./siteconf20161231-6772-1aisz4k.rb extconf.rb  creating Makefile    make "DESTDIR=" clean  make "DESTDIR="  generating debug_inspector-i386-mingw32.def  compiling debug_inspector.c  linking shared-object debug_inspector.so    make "DESTDIR=" install  /usr/bin/install -c -m 0755 debug_inspector.so ./.gem.20161231-6772-1khvo2o  make: execvp: /usr/bin/install: Permission denied  make: *** [install-so] Error 127    make install failed, exit code 2  

Rspec error in session devise with point system

Posted: 31 Dec 2016 02:41 AM PST

I implemented point system. User.point increases by 2 when he does login. My devise session controller is below.

    class Users::SessionsController < Devise::SessionsController          after_action :add_point, only: [:create]           # POST /resource/sign_in           def create             super           end          private          def add_point            resource.rewards.create(point: 2)       end      end  

and My spec/controllers/users_controller_spec.rb is below.

   RSpec.describe UsersController, type: :controller do     describe 'adds 2 point with login' do       before do        @user=create(:user)        @request.env["devise.mapping"] = Devise.mappings[:user]      end      it 'adds 2 point in one day if two times login' do        expect{post :create, params: {email: @user.email ,password: @user.password} }.to change {@user.points}.by(0)     end     it 'adds 4 point in two day ' do        expect{post :create, params: {email: @user.email ,password: @user.password} }.to change {@user.points}.by(2)     end    end    end  

and my model/user.rb is below.

   class User < ActiveRecord::Base           def points            self.rewards.sum(:point)           end    end  

When I did rspec command , I had this error.

       Failure/Error: expect{login_user(@user)}.to change {@user.points}.by(2)         expected result to have changed by 2, but was changed by 0  

I confirmed that @user.points increased by 2 in view of this application. Why do I have this error? Please tell me.

Error while adding username to my rails web app(devise gem)

Posted: 31 Dec 2016 02:08 AM PST

I have a certain error bugging my head during adding username in my rails web app.

I did what it says in link: https://rubyonrailshelp.wordpress.com/2014/01/07/adding-a-username-to-the-user-admin-model/

There seems a error in browser like:

NoMethodError in Devise::RegistrationsController#edit     undefined method `for' for #<Devise::ParameterSanitizer:0xa8342f0>     def configure_permitted_parameters      devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me) }      devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email, :password, :remember_me) }      devise_parameter_sanitizer.for(:account_update) {|u| u.permit(:username, :email, :password, :password_confirmation, :current_password)} #for account update  

What making the error in application_controller.rb

Heroku Rails db migration file order and relationships

Posted: 31 Dec 2016 03:17 AM PST

I have a User model and a Role model. When I started building the app, I start by creating the User model and the migration file that was generated contain a reference to Roles:

class CreateUsers < ActiveRecord::Migration[5.0]    def change      create_table :users do |t|        t.string :first_name        t.string :last_name        t.string :username        t.string :email        t.string :password        t.string :password_digest        t.boolean :banned        t.references :role, foreign_key: true          t.timestamps      end    end  end  

Then I created the Role model which generated this migration file:

class CreateRoles < ActiveRecord::Migration[5.0]    def change      create_table :roles do |t|        t.string :title        t.integer :access_level          t.timestamps      end    end  end  

I am trying to deploy to Heroku and migrating my database per the documentation using the following command heroku run rails db:migrate (using Rails 5).

I am getting an error from Heroku saying:

heroku run rake db:migrate  Running rake db:migrate on ⬢ gentle-headland-79177... up, run.9293 (Free)  D, [2016-12-31T08:15:33.131367 #4] DEBUG -- :    (90.7ms)  CREATE TABLE "schema_migrations" ("version" character varying PRIMARY KEY)  D, [2016-12-31T08:15:33.152682 #4] DEBUG -- :    (11.5ms)  CREATE TABLE "ar_internal_metadata" ("key" character varying PRIMARY KEY, "value" character varying, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)  D, [2016-12-31T08:15:33.155373 #4] DEBUG -- :    (1.1ms)  SELECT pg_try_advisory_lock(6845940114126317925);  D, [2016-12-31T08:15:33.172106 #4] DEBUG -- :   ActiveRecord::SchemaMigration Load (1.2ms)  SELECT "schema_migrations".* FROM "schema_migrations"  I, [2016-12-31T08:15:33.178453 #4]  INFO -- : Migrating to CreateUsers (20161117083901)  D, [2016-12-31T08:15:33.181903 #4] DEBUG -- :    (0.9ms)  BEGIN  == 20161117083901 CreateUsers: migrating ======================================  -- create_table(:users)  D, [2016-12-31T08:15:33.199351 #4] DEBUG -- :    (13.4ms)  CREATE TABLE "users" ("id" serial primary key, "first_name" character varying, "last_name" character varying, "username" character varying, "email" character varying, "password" character varying, "password_digest" character varying, "banned" boolean, "role_id" integer, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_642f17018b"  FOREIGN KEY ("role_id")    REFERENCES "roles" ("id")  )  D, [2016-12-31T08:15:33.200707 #4] DEBUG -- :    (1.0ms)  ROLLBACK  D, [2016-12-31T08:15:33.202190 #4] DEBUG -- :    (1.2ms)  SELECT pg_advisory_unlock(6845940114126317925)  rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    PG::UndefinedTable: ERROR:  relation "roles" does not exist  : CREATE TABLE "users" ("id" serial primary key, "first_name" character varying, "last_name" character varying, "username" character varying, "email" character varying, "password" character varying, "password_digest" character varying, "banned" boolean, "role_id" integer, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_642f17018b"  FOREIGN KEY ("role_id")    REFERENCES "roles" ("id")  )  

From my understanding, it appears Heroku is expecting Role to be defined first then User.

Why is it on my local machine, I can do db:migrate fine but on Heroku it fails?

Difference between Sqlite3 and Postgresql perhaps?

How do I go about solving this deployment problem?

Do I just rename my create_role migration file to have an earlier timestamp than the create_user migration file? Is that even recommended practice ? :D

Update

I did a git clone of my repository to a Desktop folder on my iMac.

Then I ran rails db:migrate on that new local copy.

No error whatsoever. All db migrations ran, all the tables are in place along with all the relationships. Something's really messed up on the Heroku end.

Completed 500 Internal Server Error in ...NameError (uninitialized constant PictureUploader::Uploader

Posted: 31 Dec 2016 12:21 AM PST

I am very new to ask the question here, hope I am following the rules correctly:

I am getting 500 server error at development env., it stated NameError with uninitialized constant for Picture uploader, BUT, most time, if I re-start the Browser (Chrome or Safari), this issue will be gone.

I am using: Rails 4.2.7.1, ruby 2.3.1p112, 'carrierwave','~> 1.0, 'mini_magick','4.3.6', rails s on puma

Is this issue possibly related to I18n locale? since I start to got this error after I have the I18n gem installed, and often happen if I changed the locales/*.yml content.

thanks you

How to avoid unicorn workers getting killed if they are processing?

Posted: 31 Dec 2016 12:05 AM PST

Titles says it all, I have some unicorn workers that handle large requests and when I load my rails app, I can't restart my app until these workers complete their tasks.

Is there a cleaner way to tell the unicorn workers to not get SIGKILLed when I do a restart of my unicorn workers?

Browser treats Ruby on Rails html.erb files as XML files

Posted: 31 Dec 2016 02:59 AM PST

I'm getting an error loading my page for viewing and editing a model in a view. It looks like the image below.

enter image description here

The files in question are edit.html.erb and show.html.erb for my notifications.

Here are my routes for this notifications model:

resources :notifications  get     'notification_settings' => 'notifications#edit'  

It should be creating a notification object (for my settings) in a has_one relationship with user.

Why would the browser think these are XML files that aren't formatted right? My other Views all load correctly.

redirect from non-www to www with https on elastic beanstalk using nginx for a ruby on rail application [migrated]

Posted: 30 Dec 2016 11:34 PM PST

I have a ruby on rails application setup on AWS elastic beanstalk using nginx and puma, my requirement is to redirect all my requests from http://example.com or http://www.example.com or https://example.com to https://www.example.com. Also I don't want request from my subdomains to be redirected to www, like I don't want http://subdomain.example.com to be redirected to https://www.expample.com or https://www.subdomain.example.com.

Using the link

How to get Elastic Beanstalk nginx-backed proxy server to auto-redirect from HTTP to HTTPS?

I was able to redirect all my requests from http to https but this does not redirect non www to www requests.

undefined method `events' for nil:NilClass

Posted: 30 Dec 2016 11:24 PM PST

I was working with nested attributes, everything seemed to be fine until when I submitted my information and I got this error. It says it is in my EventsController file:

class EventsController < ApplicationController        def new          @event = Event.new          @event.songs.build      end        def index          @songs = Song.all      end        def show        @event = Event.find(params[:id])        @songs = @event.songs.paginate(page: params[:page])      end        def create          @event = current_user.events.build(event_params)          if @event.save              flash[:success] = "Event Created!"              redirect_to user_path(@event.user)          else              render 'welcome#index'          end      end        def destroy      end        private           def event_params          params.require(:event).permit(:name, :partycode, song_attributes: [:event_id, :artist, :title, :genre, :partycode])        end  end  

Here is my new.html.erb file in my songs view(handles song submission based on selected event)

<br>  <br>  <div class ="container">    <div class="jumbotron">    <%= form_for Event.new do |f| %>      <h3>Enter a song:</h3>      <%= f.fields_for :songs, Song.new do |song_form| %>          <%= song_form.collection_select(:event_id, Event.all, :id, :name) %>        <%= song_form.text_field :artist, placeholder: "Artist" %>        <%= song_form.text_field :title,  placeholder: "Title" %>        <%= song_form.text_field :genre,  placeholder: "Genre" %>      <% end %>      <%= link_to_add_fields "Add Song", f, :songs %>      <%= f.text_field :partycode %>      <%= f.submit "Submit", class: "btn btn-primary" %>    <% end %>    </div>  </div>  

The link_to_add_fields method is defined in my ApplicationHelper.rb file:

module ApplicationHelper    def link_to_add_fields(name, f, association)      new_object = f.object.send(association).klass.new      id = new_object.object_id      fields = f.fields_for(association, new_object, child_index: id) do |builder|        render("songs_fields", f: builder)      end      link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})    end  end  

current_user is defined in Session_helper.rb file:

module SessionsHelper      # Logs in the given user.    def log_in(user)      session[:user_id] = user.id    end      def createEvent(event)      session[:event_id] = event.id    end          # Returns the current logged-in user (if any).    def current_user      @current_user ||= User.find_by(id: session[:user_id])    end    # Returns true if the user is logged in, false otherwise.    def logged_in?      !current_user.nil?    end      def log_out      session.delete(:user_id)      @current_user = nil    end    end  

Finally, here is my songs_fields file that generates fields only when a user clicks a link that says 'Add songs'

<fieldset>      <%= f.text_field :artist, placeholder: "Artist" %>    <%= f.text_field :title,  placeholder: "Title" %>    <%= f.text_field :genre,  placeholder: "Genre" %>  </fieldset>  

I feel as though this is the last portion before I get everything in my app to work! So help on this would be tremendous :D

Rails image assets - postpending ")<image.png and breaking image URL

Posted: 30 Dec 2016 09:45 PM PST

I've run into a strange situation with leaflet-rails and its marker-icon.png asset that is bundled with the gem. In my app, I have included my own version of this file in my assets/images folder, which is ahead of the gem's version in Rails.application.config.assets.paths.

When I run this in production, I see the following:

http://beta.pitot.io/flights/2035

As you can hopefully see on the map, the marker appears in HTML as:

http://beta.pitot.io/assets/marker-icon-f8cd76868804022ae9aeb0e99417ccb0ced2db3a9b4e107ec44f4a43ee9a6635.png")marker-icon.png

Including the quote and the paranthese before marker-icon.png.

This doesn't appear in development without asset precompilation, and didn't previously occur before an update to the leaflet gem.

Does anyone know what might be causing this?

Cannot run cap production deploy:initial with Net::SSH::AuthenticationFailed: Authentication failed for user?

Posted: 31 Dec 2016 06:29 AM PST

I tried to deploy my rails app from my mac into the server on digital ocean (using github).

So when i ran cap production deploy:initial for the firstime i got this error

** Invoke production (first_time)  ** Execute production  ** Invoke load:defaults (first_time)  ** Execute load:defaults  ** Invoke bundler:map_bins (first_time)  ** Execute bundler:map_bins  ** Invoke deploy:set_rails_env (first_time)  ** Execute deploy:set_rails_env  ** Invoke rvm:hook (first_time)  ** Execute rvm:hook    cap aborted!  Net::SSH::AuthenticationFailed: Authentication failed for user deploy@myip    /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/net-ssh-4.0.0/lib/net/ssh.rb:250:in `start'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/connection_pool.rb:59:in `call'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/connection_pool.rb:59:in `with'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/netssh.rb:155:in `with_ssh'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/netssh.rb:108:in `execute_command'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/abstract.rb:141:in `block in create_command_and_execute'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/abstract.rb:141:in `tap'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/abstract.rb:141:in `create_command_and_execute'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/abstract.rb:55:in `test'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/capistrano-rvm-0.1.2/lib/capistrano/tasks/rvm.rake:21:in `block (3 levels) in <top (required)>'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/abstract.rb:29:in `instance_exec'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/backends/abstract.rb:29:in `run'  /Users/manjarb/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/sshkit-1.11.5/lib/sshkit/runners/parallel.rb:12:in `block (2 levels) in execute'  

But I already added my server id_rsa.pub to repository Deploy Key. And when i test by cloning my repo from ssh key it works fine without any problem.

this is my deploy.rb

# config valid only for current version of Capistrano  lock "3.7.1"    set :repo_url,        'git@github.com:myrepo.git'  set :application,     'appname'  set :user,            'deploy'  set :puma_threads,    [4, 16]  set :puma_workers,    0    # Don't change these unless you know what you're doing  set :pty,             true  set :use_sudo,        false  set :stage,           :production  set :deploy_via,      :remote_cache  set :deploy_to,       "/home/#{fetch(:user)}/apps/#{fetch(:application)}"  set :puma_bind,       "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"  set :puma_state,      "#{shared_path}/tmp/pids/puma.state"  set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"  set :puma_access_log, "#{release_path}/log/puma.error.log"  set :puma_error_log,  "#{release_path}/log/puma.access.log"  set :ssh_options,     { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa.pub) }  set :puma_preload_app, true  set :puma_worker_timeout, nil  set :puma_init_active_record, true  # Change to false when not using ActiveRecord    namespace :puma do    desc 'Create Directories for Puma Pids and Socket'    task :make_dirs do      on roles(:app) do        execute "mkdir #{shared_path}/tmp/sockets -p"        execute "mkdir #{shared_path}/tmp/pids -p"      end    end      before :start, :make_dirs  end    namespace :deploy do    desc "Make sure local git is in sync with remote."    task :check_revision do      on roles(:app) do        unless `git rev-parse HEAD` == `git rev-parse origin/master`          puts "WARNING: HEAD is not the same as origin/master"          puts "Run `git push` to sync changes."          exit        end      end    end      desc 'Initial Deploy'    task :initial do      on roles(:app) do        before 'deploy:restart', 'puma:start'        invoke 'deploy'      end    end      desc 'Restart application'    task :restart do      on roles(:app), in: :sequence, wait: 5 do        invoke 'puma:restart'      end    end      before :starting,     :check_revision    after  :finishing,    :cleanup  end  

So how can i fix this?

Thanks!

rails 5 rspec 3.5 stub_request regex where url params exists and does not exist

Posted: 30 Dec 2016 08:30 PM PST

I need to stub a request with 2 variations, for example...

stub_request(:any, %r{/.*amazonservices.com.*/}).to_return(body: order_fixture_with_pages, status: 200, headers: { 'Content-Type': 'text/xml' })  

This is the url from Amazon...

https://mws.amazonservices.jp/Orders/2013-09-01    ?AWSAccessKeyId=0PB842EXAMPLE7N4ZTR2    &Action=ListOrdersByNextToken    &MWSAuthToken=amzn.mws.4ea38b7b-f563-7709-4bae-87aeaEXAMPLE    &SellerId=A2986ZQ066CH2F    &Signature=ZQLpf8vEXAMPLE0iC265pf18n0%3D    &SignatureVersion=2    &SignatureMethod=HmacSHA256    &NextToken=2YgYW55IGNhcm5hbCBwbGVhc3VyZS4%3D    &Timestamp=2013-09-05T18%3A12%3A21.687Z    &Version=2013-09-01  

I want to build a regex that searches for NextToken. If it exists, I want to stub one way, if it doesn't, verified, I want to do something different.

So far I am working with https?:\/\/[\S]+

Thoughts?

NestedAttributes Not Functioning

Posted: 30 Dec 2016 09:18 PM PST

I have Events and Songs. When a User logs in they can look at all of their events and that certain event's partycode that were created, click on one and see all the songs for that Event. Now, when the user is not logged in they can add songs to a certain event based on a certain partycode. I am unable to add fields and submit those added fields to the submit button, but I can submit the first set of fields.

new.html.erb(Page that handles selecting an event and adding songs)

<br>  <br>  <div class ="container">    <div class="jumbotron">    <h2> Select an event to add songs to: </h2>    <%= form_for Song.new do |f| %>      <%= f.collection_select(:event_id, Event.all, :id, :name) %>      <h3> Enter your song </h3>        <%= f.text_field :artist, placeholder: "Artist" %>        <%= f.text_field :title,  placeholder: "Title" %>        <%= f.text_field :genre,  placeholder: "Genre" %>        <h2> Enter the partycode for that event: </h2>      <%= form_for Event.new do |f| %>        <h4><%= link_to_add_fields "Want to add more songs click here", f, :songs %></h4>          <%= f.text_field :partycode %>        <%= f.submit "Submit", class: "btn btn-primary" %>      <% end %>      <% end %>    </div>  </div>  

The link_to_add_fields method is in the application_helper.rb

module ApplicationHelper    def link_to_add_fields(name, f, association)      new_object = f.object.send(association).klass.new      id = new_object.object_id      fields = f.fields_for(association, new_object, child_index: id) do |builder|        render("songs_fields", f: builder)      end      link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})    end  end  

The songs_fields partial is defined as follows:

<fieldset>    <%= text_field_tag "songs[][artist]" %>    <%= text_field_tag "songs[][title]" %>    <%= text_field_tag "songs[][genre]" %>  </fieldset>  

Here is my event model:

class Event < ApplicationRecord    belongs_to :user    has_many :songs, dependent: :destroy      accepts_nested_attributes_for :songs, allow_destroy: true      validates :name, presence: true    validates :partycode, presence: true, length: {minimum: 5}  end  

Finally, I have defined a coffeescript file for adding the extra fields:

$(document).on 'click', 'form .add_songs', (event) ->    time = new Date().getTime()    regexp = new RegExp($(this).data('event_id'), 'g')    $(this).before($(this).data('songs').replace(regexp, time))    event.preventDefault()  

All I want to do is have those extra fields be submitted to my events database which holds the songs. I have posted many questions on this matter but I haven't gotten an answer that was able to fix what I have been looking for, and after spending hours on this code I would really like to find a solution. enter image description here

Search ruby gems scoped by source URL

Posted: 30 Dec 2016 06:18 PM PST

I'm looking for a way to obtain a list of all the gems in a private source website, using a syntax like this (fake url provided for security reasons):

gem search -r --source https://www.myexample.com/gems-repo/  

just shows a list of all the gems from all the sources I have added to my gems config (thus a really big list, https://rubygems.org/ alone bears hundreds), the source switch in the command above doesn't seem to be used at all. Is there a way to accomplish this task? Thank you.

Can I render this collection without using .each()?

Posted: 30 Dec 2016 05:35 PM PST

I'm new to ruby, but it seems like if I have a collection of things, I should be able to render them either in a loop or by defining a :collection.

Here, each garden may have many plants assigned to it. I have a partial that renders plants in a "card" layout. This view correctly renders the plants for each garden:

views/gardens/show.html.haml

.row.plant-cards    - @garden.plants.each do |plant|      = render("shared/plants/card", {plant: plant, garden: @garden} )  

views/shared/plants/_card.html.haml

.col-md-2    .plant.thumbnail.text-center      = button_to("+", add_to_garden_path(plant, @garden.id), {method: :post ,remote: true})      = link_to(plant) do        = image_tag("http://lorempixel.com/g/150/150/food/",:alt => plant.name)        %h4.plant__title.caption= plant.name  

I am trying to update the rendered plants on the garden page via ajax. It seems that I need to stick the output of the rendered plant "cards" in the .html() function and using the .each() seems clumsy for that. It seems like I should be able to set the plants as the :collection like I'm trying to do below, but that doesn't work:

views/plants/add_to_garden.js.erb (sorry for mixing haml/erb - I'm exploring that too)

<% flash.each do |key, message| %>    $("#flash").html("<%= j render partial: "shared/flash_message", locals: {key: key, message: message } %>");  <% end %>  $(".plant-cards").html("<%= j render :partial => 'shared/plants/card', :collection => @garden.plants, :locals => {garden: @garden} %>");  

When I make the ajax call to my application I get this runtime error:

Started POST "/plants/2/add_to_garden/1" for ::1 at 2016-12-30 20:32:18 -0500  Processing by PlantsController#add_to_garden as JS    Parameters: {"authenticity_token"=>"qJU/CEZudZFP9l6r1qdAlXJQrfY7fB0aZHmjRJh2yQO0IzxilP47mP2UjDDAmBNJouFtoAWkv/hJ2gCNR5BpgQ==", "id"=>"2", "garden_id"=>"1"}    Garden Load (0.3ms)  SELECT  `gardens`.* FROM `gardens` WHERE `gardens`.`id` = 1 LIMIT 1    Plant Load (0.2ms)  SELECT  `plants`.* FROM `plants` WHERE `plants`.`id` = 2 LIMIT 1     (0.1ms)  BEGIN    SQL (0.2ms)  INSERT INTO `gardens_plants` (`garden_id`, `plant_id`) VALUES (1, 2)     (160.8ms)  COMMIT     (0.2ms)  BEGIN    User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1     (0.1ms)  COMMIT    Rendered shared/_flash_message.html.erb (0.3ms)    Plant Load (0.5ms)  SELECT `plants`.* FROM `plants` INNER JOIN `gardens_plants` ON `plants`.`id` = `gardens_plants`.`plant_id` WHERE `gardens_plants`.`garden_id` = 1    Rendered shared/plants/_card.html.haml (29.7ms)    Rendered plants/add_to_garden.js.erb (42.3ms)  Completed 500 Internal Server Error in 238ms (ActiveRecord: 162.9ms)    NameError - undefined local variable or method `plant' for #<#<Class:0x007fdf9be0f6c8>:0x007fdf9bce6350>:    app/views/shared/plants/_card.html.haml:3:in `_app_views_shared_plants__card_html_haml___4163891484537289381_70299132319600'    ...  

How to fix Ransack undefined method “_eq”, when using ActiveAdmin

Posted: 30 Dec 2016 05:20 PM PST

NoMethodError in Admin::Transacoes#index  Showing /usr/local/rvm/gems/ruby-2.3.0/bundler/gems/activeadmin-0ac35b7ff052/app/views/active_admin/resource/index.html.arb where line #2 raised:    undefined method `cliente_id_eq' for #<Ransack::Search:0x00000004e964a8>  

There is a pattern "_eq" for each undefined method :

class Cliente < ActiveRecord::Base  self.table_name = "cliente"  self.primary_key = 'Cod_Cliente'  has_many :transacao    end    class Transacao < ActiveRecord::Base    self.table_name = "transacao"    self.primary_key = 'Numero_Transacao'    belongs_to :cliente    belongs_to :funcionario    belongs_to :aluguel  end  

I'm using rails with a ready-made database running in another (remote) application and fields are no default of rails

any ideas?

Rails has_many nested attributes + paperclip gem

Posted: 31 Dec 2016 01:58 AM PST

I have this model:

class Project < ApplicationRecord      acts_as_taggable      has_many :documents, dependent: :destroy      accepts_nested_attributes_for :documents  end  

and this model:

class Document < ApplicationRecord      belongs_to :project,inverse_of: :document, dependent: :destroy      has_attached_file :document, styles: {thumbnail: "60x60#"}      validates_attachment :document, content_type: { content_type:     "application/pdf" }  end  

This is my methods of the projects_controller.rb file:

def new      @project = Project.new      @project.documents.build   end  def project_params        params.require(:project).permit(:title, :resume, :documents => [:id,:name,:description,:date,:local,:document],  end  

This is my index view of the project:

<td><%= project.title %></td>   <td><%= project.resume %></td>   <td><%= project.documents.name %></td>   <td><%= project.documents.description %></td>   <td><%= project.documents.date %></td>   <td><%= project.documents.local %></td>   <td><%= project.documents.document_file_name %></td>   <td><%= link_to 'Download', project.documents.document.url(:original, false) %> </td>  

When I create a document in document view, the document is created, but when I want to create the documents attributes in the project view it gives me this error:

undefined method 'description' for ActiveRecord::Associations::CollectionProxy []

What am I doing wrong?

Rails - connecting to postgres with url, role does not exist

Posted: 30 Dec 2016 04:43 PM PST

I'm attempting to deploy a Rails 5 app using Capistrano, and I'm hung up on the db:migrate step.

Specifically, when my scripts attempt to run db:migrate I get the error:

ActiveRecord::NoDatabaseError: FATAL: role "admin" does not exist

My database.yml file looks like this for the production block:

production:    adapter: postgresql    encoding: unicode    # For details on connection pooling, see rails configuration guide    # http://guides.rubyonrails.org/configuring.html#database-pooling    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>    url: <%= ENV['DATABASE_URL'] %>  

and my database_url takes the form of:

postgresql:://mydb_user:mydbuser_pass@localhost/db_name  

With mydb_user, mydbuser_pass, and db_name substituted in with my own correct values.

Inside of postgres I can see these permissions on my database:

 db_name | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =Tc/postgres + postgres=CTc/postgres + mydb_user=CTc/postgres  

Which I think means that mydb_user has the permissions necessary for using my database.


Now, the user I'm logged in as during the capistrano deploy does have the username of 'admin', which leads me to believe that I fundamentally don't understand something about postgres roles. Why would my currently logged in user have anything to do with the postgres connection when I've given my username and password via the database url for a specific postgres user I've already created? Is this saying that my ubuntu username needs to match mydb_user in order to login? How do I fix this error specific to rails and database urls with postgres?

No comments:

Post a Comment