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?

Friday, December 30, 2016

How do I get RSpec and Cucumber tests to run in an app using both Mongoid and ActiveRecord? | Fixed issues

How do I get RSpec and Cucumber tests to run in an app using both Mongoid and ActiveRecord? | Fixed issues


How do I get RSpec and Cucumber tests to run in an app using both Mongoid and ActiveRecord?

Posted: 30 Dec 2016 07:25 AM PST

My team's project is a Rails 4.2 app using Mongoid 4. A new feature we are adding requires us to read data from a Postgres DB and use those records in the app through an intermediary object. In other words, our app will play with ActiveModel objects (non-persisted) that contain a mix of data from Mongoid models and ActiveRecord models, and thus can do all the normal cool Rails stuff with Controllers and Views, etc. (We think it's clever.) The intention right now is that we will never write to the SQL tables, just read. Any new data stored will be in mongodb.

For my development environment, the first steps seemed pretty straight-forward:

  • I added pg to the gemfile
  • I added require "active_record/railtie" to application.rb
  • I made my new models in the normal ActiveRecord way (although since I was working with an existing database, I changed the class names to something more meaningful and set the table names accordingly)
  • I added a database.yml file (we didn't need one with mongoid) with all the correct postgres info
  • I created the schema.rb file using rake db:schema:dump. That took a while to figure out I needed it, but I got there.

Using the rails console, I was able to prove to myself that I could search/find objects in both databases. So far so good.

When I first fired up the rspec tests, there were tons of failures related to validation errors because "records already existed with that name". Long investigation story short, I fixed by setting all DatabaseCleaner calls to be DatabaseCleaner[:mongoid], and that got rspec passing again. (I still have no idea what was actually happening behind the scenes.)

BUT, Cucumber (feature) tests? I can't even get them started. It keeps saying:

Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=test  

No! All those migrations we have are for MONGO. There are no SQL/ActiveRecord migrations. Not surprisingly, that rake fails:

rake aborted! ArgumentError: wrong number of arguments (2 for 0).  

I tried this series of commands:

rake db:drop RAILS_ENV=test  rake db:create RAILS_ENV=test  rake db:schema:load RAILS_ENV=test  

but cucumber still gives the same migration pending error.

So I'm stuck! I haven't found anyone doing what we're trying to do. I know there HAS to be someone, I just haven't found the right search terms, apparently.

The worst part of all this is I had no intention of even using an ActiveRecord test database at all, I was simply going to mock those records in my tests. How can I tell the app, "I only need ActiveRecord for runtime, not testing. Stop looking at the migrations, ActiveRecord, those aren't for you!"

I have run out of ideas and words to search with. I've been trying to solve this problem for a couple of days now and have tried SO many different things, please forgive me if I've left some of those out here. Any assistance would be greatly appreciated.

Unexplicable InvalidURIError after controller testing

Posted: 30 Dec 2016 07:03 AM PST

I was testing my Rails 5.0 application with the following code:

  test "destroy should require logged-in user" do      assert_no_difference 'AtpSelection.count' do        delete :destroy, params: { id: atp_selections(:selection_1) }      end      assert_redirected_to login_url    end  

but the test kept failing:

ERROR["test_destroy_should_require_logged-in_user", AtpSelectionsControllerTest, 1.9559332270000596]   test_destroy_should_require_logged-in_user#AtpSelectionsControllerTest (1.96s)  URI::InvalidURIError:         URI::InvalidURIError: bad URI(is not URI?): http://www.example.com:80destroy  

So, in order for the test to pass, I had to change my code using instead the following code:

  test "destroy should require logged-in user" do      assert_no_difference 'AtpSelection.count' do        delete atp_selection_path(atp_selections(:selection_1))      end      assert_redirected_to login_url    end  

I have no idea why I could not make the test pass calling delete directly on the controller action :destroy. I made this same choice in other tests I created before for other controllers and they succeed without raising errors.

What i wrong with my html.erb file?

Posted: 30 Dec 2016 07:08 AM PST

from the code below, I get the following error:

/home/ubuntu/workspace/portfolio/app/views/projects/_project_form.html.erb:36: syntax error, unexpected keyword_ensure, expecting end-of-input

because it is a syntax error, I am guessing I wont need to provide other details but if you guys need me to post more feel free to ask.

    <%= form_for @project do |f| %>    <% if @project.errors.any? %>      <div id="error_explanation">        <h2>          <%= "#{pluralize(@project.errors.count, "error")} prohibited this project from being saved:" %>        </h2>        <ul>          <% @project.errors.full_messages.each do |msg| %>            <li>              <%= msg %>            </li>          <% end %>        </ul>      </div>    <% end %>    <div class="field">      <%= f.label :client %>        <p>          <%= @project.client.name %>        </p>        <%= f.hidden_field:note_id, value: @project.client.id  %>      <% end %>    </div>    <div class="field">      <%= f.label :project_description %>      <%= f.text_area :project_description %>    </div>    <div class="field">      <%= f.label :project_timescale %>      <%= f.text_field :project_timescale %>    </div>    <div class="actions">      <%= f.submit 'Save' %>    </div>    <% end %>  

Database configuration errors while deploying Rails app to Heroku

Posted: 30 Dec 2016 06:55 AM PST

I'm using Rails 4.2.3

I received the classic "sqlite not supported" error initially, and then removed all references to sqlite.

Now I'm getting:

remote:        Cleaning up the bundler cache.  remote: -----> Detecting rake tasks  remote: -----> Preparing app for Rails asset pipeline  remote:        Running: rake assets:precompile  remote:        rake aborted!  remote:        URI::InvalidURIError: bad URI(is not URI?): ://user:pass@127.0.0.1/dbname  

My database.yml looks like this:

production:    url: <%= ENV['CLEARDB_DATABASE_URL'] %>  

I've also tried:

production:    url: <%= ENV['DATABASE_URL'] %>    production:    encoding: utf8    pool: 15  

How can i call model method in Rails 5 with ajax?

Posted: 30 Dec 2016 06:53 AM PST

I've a Task model in Rails with this method

    def notify(user)      Task.where(assignee: user).where(notified: false).count  end  

that returns the number of particular tasks. I need to call it via Ajax, how can i do it? I know that i could use it in a controller method and call Ajax to controller (i know how to do this) but then the controller method would be attainable via url.

When is touch_record (belongs_to.rb) called?

Posted: 30 Dec 2016 07:38 AM PST

In this method from belongs_to.rb, def self.touch_record(o, foreign_key, name, touch) I am trying to get the 'o' class.

I try :

bundle show activerecord then open 'thepathgivenbymyfirstcommand' and put a 'binding.pry' in the method

Finally, I moved into a rails project (with belongs_to association already created) and try to update/destroy as they said here :":touch If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or destroyed. If you specify a symbol, that attribute will be updated with the current time in addition to the updated_at/on attribute."

but nothing happened, I never stop at the "binding.pry" to get the 'o' variable class.

Do you have any advice ?

Sass::Engine.new Rails | Compiled css file has code from the scss.erb template file causing the css file to have errors

Posted: 30 Dec 2016 06:31 AM PST

I have made use of the Sass engine in rails to produce a custom css file for each element a user can add to the site.

This is my generate css code

def generate_css       Sass::Engine.new(asset_source, {            syntax: :scss,            cache: false,            read_cache: false,            style: :compressed         }).render  end  

The template file it uses is just a list of variables and a sass if statement to check which mix-in to use. This when compiled seems to keep around 22 lines of code from the template file.

This isn't a major problem as the css file still renders in the browser fine but it is annoying knowing I have incorrect/ erroneous files.

Any ideas on how to trim/remove reformat the final compiled css?

How to make this link to send PUT request.?

Posted: 30 Dec 2016 06:33 AM PST

This is a helper method to generate a link in the_comments gem. I want to make it put request.

def approved_comment    "<p class='reply'><a href='/comments/#{@comment.id}/approve_comment'>#{ t('the_comments.approve') }</a>"   end  

If any one know how to make it PUT request please help me.

Using Cassandra in Rails App

Posted: 30 Dec 2016 05:42 AM PST

I have a couple of questions about working with Ruby on Rails and Cassandra. I have a PostgreSQL database and a Cassandra database separate from my Rails application. I would like to access Cassandra to make some queries through my Rails application.

What is the recommended way of Cassandra integration into a Rails app ?

Is there any reference implementation?

Regards,

Rails factory_girls and validation issue

Posted: 30 Dec 2016 06:07 AM PST

I have HABTM association

my models

 class Ssr < ActiveRecord::Base      has_and_belongs_to_many :ssr_groups      validates :ssr_groups, presence: true   end    class SsrGroup < ActiveRecord::Base    has_and_belongs_to_many :ssrs, dependent: :destroy    validates :name, presence: true  end  

my factories

  FactoryGirl.define do    factory :ssr do      type 'type'       ssr_groups     end   end    FactoryGirl.define do    factory :ssr_group, class: 'SsrGroup', aliases: [:ssr_groups] do      name { SecureRandom.hex }    end  end  

My problem is when i want to create FactoryGirl.create(:ssr)

i have got NoMethodError: undefined method each for #<SsrGroup:0x007fbfdf792100>

Why it happens?

/Users/user/.rvm/rubies/default/bin/ruby: No such file or directory -- script/rails (LoadError)

Posted: 30 Dec 2016 05:32 AM PST

I want to use Ruby with Netbeans IDE. But I get error when I start Ruby on Rails project in console:

/Users/user/.rvm/rubies/default/bin/ruby: No such file or directory -- script/rails (LoadError)  

But there is a file:

file /Users/user/.rvm/rubies/default/bin/ruby  /Users/user/.rvm/rubies/default/bin/ruby: Mach-O 64-bit executable x86_64  

Do you know how I can solve this issue?

Production error env

Posted: 30 Dec 2016 06:57 AM PST

In development mode the rails normally run, but not in production. I already ran rake db: migrate

file production.log

[1m[36mActiveRecord::SchemaMigration Load (0.9ms)[0m  [1mSELECT "schema_migrations".* FROM "schema_migrations"  

Rails navbar conditional and getting No route matches in root_path

Posted: 30 Dec 2016 05:46 AM PST

Hello I want to show the search form inside the navbar only in the index page of products and the show page of the product. The thing is that it is showing on both the index page and the show page but when I click home to go to the root_path I get the following error:

No route matches {:action=>"show", :controller=>"products"} missing required keys: [:id]

How can I avoid that? This is my code in the application.html.erb:

<% if current_page?(products_path) || (product_path) %>        <div class="col-sm-3 col-md-3 pull-right">          <form class="navbar-form" role="search">          <div class="input-group">              <input type="text" class="form-control" placeholder="Search" name="search_term" id="search_term">              <div class="input-group-btn">                  <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>              </div>          </div>          </form>          </div>      <% end %>

Rails: how to check CSS or JS code code from a string?

Posted: 30 Dec 2016 05:34 AM PST

In a code string I have stored a piece of code, can be CSS, SASS, SCSS, JavaScript or CoffeeScript.

I need to check if the syntax is correct. Currently I found a ugly hack which works. Do you know a better solution?

def check_js    if language == 'coffee'      CoffeeScript.compile code    else      Uglifier.compile code    end  rescue ExecJS::RuntimeError => e    errors.add :code, e.message  end    def check_css    if language == 'css'      Sass::CSS.new(code).render    else      Sass.compile code, syntax: language.to_sym    end  rescue Sass::SyntaxError => e    errors.add :code, e.message  end  

FriendlyID for child

Posted: 30 Dec 2016 05:32 AM PST

I have a Project model that belongs to a User. A User has_many Projects. I have setup FriendlyID according to the gem instructions for User model, however it is not working in this scenario.

<%= link_to gravatar_for(project.user, size: 50), project.user %>  

The above creates a link with the numerical ID of the user (project.user) instead of a friendly URL (i.e. http://localhost:3000/users/102 instead of what I want, http://localhost:3000/users/*random-gen-string*).

User.rb file:

class User < ApplicationRecord    extend FriendlyId    friendly_id :generated_slug, use: :slugged      def generated_slug      require 'securerandom'      @random_slug ||= persisted? ? friendly_id : SecureRandom.hex(15)    end  

I think the problem is that project.user is set in the projects_controller.rb to the user ID (via current_user.projects.build...). If I could somehow access the Friendly ID for User in the projects_controller.rb I may be able to save it in the database and access it like project.user_friendly_id. Not sure..

Relevant code in projects_controller:

def create   @project = current_user.projects.build(project_params)   # code  end  

What is the best way to go about making the above link link to the Friendly ID and not the user (i.e. http://localhost:3000/users/*random-gen-string* is what I want instead of http://localhost:3000/users/102)?

getting error, Mysql2::Error: You have an error in your SQL syntax in rails?

Posted: 30 Dec 2016 04:44 AM PST

What needs to be changed in the below queries?. i want all those employees whose date_of_leaving is null or the date_of_leaving is in between the past 60 days or the date_of_leaving is greater than or equal to the Date.today or current date.

employees = @company.employees.where('date_of_leaving BETWEEN ? AND ? OR date_of_leaving IS NULL OR date_of_leaving IS >= Date.today', Date.today - 60, Date.today)  

i tried in another way also like below.

employees = Company.find(4).employees.where('date_of_leaving BETWEEN ? AND ? OR date_of_leaving IS NULL OR date_of_leaving IS >= ?', Date.today - 60, Date.today,Date.today)  

Rails, how to use a block in where statement

Posted: 30 Dec 2016 06:33 AM PST

Taken from this stackoverflow-question, one can use a block for a query, like this:

Consumer.find do |c|    c.id == 3  end  

I want to do the same with a "where" query, for example:

mainCustomers = Customer.where do |c|   c.id == c.main  end  

When I do this, I get something like this:

=> #<ActiveRecord::QueryMethods::WhereChain:0x0055a057444560 @scope=#<ActiveRecord::Relation   

I can't use ActiveRecord methods, for example:

irb(main):013:0> mainCustomers.last  NoMethodError: undefined method `last' for #<ActiveRecord::QueryMethods::WhereChain:0x0055a057444560>  

or

irb(main):014:0> mainCustomers.count  NoMethodError: undefined method `count' for #<ActiveRecord::QueryMethods::WhereChain:0x0055a057444560>  

What is the correct way for using blocks in a where statement?

Adding a scope to ruby gem validation of uniqueness

Posted: 30 Dec 2016 04:32 AM PST

acts-as-taggable-on gem has a built-in uniqueness validation:

validates_uniqueness_of :name, if: :validates_name_uniqueness?    def validates_name_uniqueness?    true  end  

How do I add a scope to this validation?

I want to add scope: :user_id and don't know how to edit a gem source code.

Two levels of nested attributes and strong parameters

Posted: 30 Dec 2016 03:21 AM PST

I've ported a Rails app from Rails 3 to Rails 4 and most things work now, except for a problem with two levels of nested attributes:

  • I have ProductGroups, Variants and Prices.
  • Each ProductGroup has one or more variants. One of them is the master variant.
  • Each variant has many prices (one for each region).

I have a controller that updates ProductGroups. When the ProductGroup is updated, the master variant is updated at the same time. And prices in the master variant are also updated.

Here's a test that describes what's expected to happend:

test "should update master variant" do      login_as accounts(:johnny_admin)        p = ProductGroup.find product_groups(:toothbrush).id      assert_equal "10123", p.artno      assert_equal "10123", p.master_variant.artno        puts(p.master_variant.prices.to_a.to_s)        post :update,           id: product_groups(:toothbrush),           p: 'setup',           product_group: {             master_variant_attributes: {               artno: "20222",               supplier_artno: "1010",               prices_attributes: { "0": { price: "55", id: prices(:toothbrush_price_se).id } }             }           }      assert_response :redirect    assert_redirected_to edit_admin_product_group_path(p, :p => 'setup')      p = ProductGroup.find product_groups(:toothbrush).id    assert_equal "20222", p.artno    assert_equal "20222", p.master_variant.artno    assert_equal "1010", p.master_variant.supplier_artno      price = Prices.find prices(:toothbrush_price_se).id    assert_equal 55, price.price  end  

But it fails with this error:

# Running:    .......[#<Price id: 510149407, variant_id: 630858089, region_id: 102782309, price: #<BigDecimal:55d2732f50a8,'0.95E2',9(18)>, created_at: "2016-12-30 11:14:28", updated_at: "2016-12-30 11:14:28">, #<Price id: 524805804, variant_id: 630858089, region_id: 960235695, price: #<BigDecimal:55d27339c510,'0.1E2',9(18)>, created_at: "2016-12-30 11:14:28", updated_at: "2016-12-30 11:14:28">]  E    Finished in 1.279989s, 6.2501 runs/s, 20.3127 assertions/s.      1) Error:  Admin::ProductGroupsControllerTest#test_should_update_master_variant:  ActiveRecord::RecordNotFound: Couldn't find Price with ID=510149407 for Variant with ID=      app/controllers/admin/product_groups_controller.rb:150:in `update'      test/functional/admin/product_groups_controller_test.rb:103:in `block in <class:ProductGroupsControllerTest>'  

As you can see in the debug output, there is a price with ID 510149407 for that variant. And why is the ID of the variant empty?

I'm totally stuck.

Here's the permits for ProductGroup that I'm using:

  def product_group_params      prices_attributes = { :prices_attributes => [ :id, :price ] }      master_variant_attributes = { :master_variant_attributes => [        :unit, :vat, :artno, :width, :height, :depth,        :description, :in_stock, :in_stock_verified_at,        :status, :supplier_id, :supplier_artno,        :alt_supplier_id, :alt_supplier_artno,        :supplier_price, :alt_supplier_price,        :supplier_reduction, :alt_supplier_reduction,        :supplier_carriage_percentage, :alt_supplier_carriage_percentage,        :our_expenses, :percentage_markup, :taric_code_id,        :reduction_group_id, :vendor_id, :vendor_artno, :is_expired,        :show_price, :reorder_point,        :place_of_storage_a, :place_of_storage_b, :place_of_storage_c,        prices_attributes      ] }        params.require(:product_group).permit(:updated_by,                                            :title, :description, :license_code, :fixme,                                            master_variant_attributes,                                            :notes, :vat, :artno, :unit,                                            :width, :height, :depth, :in_stock, :published, :reorder_point,                                            :current_version, :changelog, :price_by_start_cost_and_per_unit,                                            :start_cost_variant_id, :unit_cost_variant_id,                                            :category_ids => [])    end  

Here's how ProductGroup relates to the master variant:

  has_one :master_variant,            -> { where(is_master: true, deleted_at: nil) },            :class_name => "Variant",            :foreign_key => 'product_group_id',            :dependent => :destroy,            :autosave => true    accepts_nested_attributes_for :master_variant  

Here's how Variant relates to Prices:

  has_many :prices, -> { order('region_id') }, :dependent => :destroy    accepts_nested_attributes_for :prices  

I will gladly post any other excerpts from the code if it is of any help, but I'm not sure what could be of interest right now.

Any hints would be much appreciated!

Error: Postgres database import in docker container

Posted: 30 Dec 2016 05:49 AM PST

I'm running a ruby on rails application in docker container. I want to create and then restore the database dump in postgres container. But I'm

Below is what I've done so far:

1) Added bash script in /docker-entrypoint-initdb.d folder. Script is just to create database:

psql -U docker -d postgres -c 'create database dbname;'

RESULT: Database created but rails server exited with code 0. Error: web_1 exited with code 0

2) Added script to be executed before docker-compose up.

# Run docker db container  echo "Running db container"  docker-compose run -d db    # Sleep for 10 sec so that container have time to run  echo "Sleep for 10 sec"  sleep 10    echo 'Copying db_dump.gz to db container'  docker cp db_dump/db_dump.gz $(docker-compose ps -q db):/    # Create database `dbname`  echo 'Creating database `dbname`'  docker exec -i $(docker-compose ps -q db) psql -U docker -d postgres -c 'create database dbname;'    echo 'importing database `dbname`'  docker exec -i $(docker-compose ps -q db) bash -c "gunzip -c /db_dump.gz | psql -U postgres dbname"  

RESULT: Database created and restored data. But another container runs while running web application server using docker-compose up.

docker--compose.yml:

version: '2'    services:      db:      image: postgres        environment:        - POSTGRES_PASSWORD=docker        - POSTGRES_USER=docker      web:      build: .      command: bundle exec rails s -p 3000 -b '0.0.0.0' -d      image: uname/application      links:        - db      ports:        - "3000:3000"      depends_on:        - db      tty: true  

Can some one please help to create and import database?

EDIT:

I've tried one more approach by adding POSTGRES_DB=db_name environment variable in docker-compose.yml file so that database will be created and after running the application (docker-compose up), I'll import the database. But getting an error: web_1 exited with code 0.

I'm confused why I'm getting this error (in first and third approach), seems to be something is messed up in docker-compose file.

How to password protect Munin directory?

Posted: 30 Dec 2016 03:19 AM PST

I followed Munin, apache and how to password protect munin and have added .htaccess file in /var/www/munin with this code

AuthType Basic  AuthName "My Protected Area"  AuthUserFile /var/www/munin/.htpasswd  Require valid-user  

I have also generated .htpasswd file with apache utils has it has the username and md5 password. Now after reloading and restarting apache, I can still see example.com/munin content.

I am running rails on example.com but I don't think that has anything to do with munin which resides on different path. Can you suggest me what I am missing out or if there is any other way using which I can password protect munin content ?

How obtain connect with OAuth 2 using Postman?

Posted: 30 Dec 2016 03:22 AM PST

My API uses the devise_token_auth (omniauth) gem for authentication in the Rails 5 backend. The frontend are using ng-token-auth (Angular 1.x).

I have all the API requests in Postman. I did the security implementation and I need authenticate Postman with every request. Devise_token_auth uses authentication with OAuth 2 and I am having difficulty to implementing this authentication.

enter image description here

For this type of authentication, using Postman, what is the process needed to obtain the connection?

How to merge multiple docx files into one docx file in rails?

Posted: 30 Dec 2016 03:09 AM PST

I have multiple docx files with same header and footer and want to merge them together to form one document keeping the header and footer intact.

Create Wistia model in Ruby on Rails

Posted: 30 Dec 2016 03:40 AM PST

I am building currently an web app where the admin will be able to post a title with a description and a link / embedded form of Wistia Video Player.

Currently my setup is:

  • Welcome Page
  • Dashboard Page with Dashboard Controller (here only the admin will be able to post, edit things, all other users can only watch/comment)

How do i create a model for this? Normally i would create a model like this:

rails g model Video title:string description:text   

But how do i implement the Wistia Video Player, so that everytime the Admin creates a new post, he will be able to link/embedded a new video?

Rails: Accessing image files after being uploaded

Posted: 30 Dec 2016 02:56 AM PST

I am writing a Ruby on Rails 5 app. I just learned how to upload an image without using paperclip,carrierwave, or refile. I have used refile in the past but for this app, I wanted to learn how to do it with out those third party gems. And it was not that difficult to do. I have successfully uploaded a file. My problem is accessing the image afterwards! I thought this would be rather simple. But NO!

I have image files being uploaded to "/public/images/page/image.jpg"

I have added "/public/images/page" to the assets path in app/initializers/assets.rb

I have tried straight img tag like this:

<img class="pic left" src="/public/images/page/mars01.jpg" alt="Mars01" />  

I get a "(No route matches [GET] "/public/images/page/mars01.jpg")" error. I have tried:

<%= image_tag "/public/images/page/#{@page.image}", class: 'pic left' %>  

basically the same as tag, get same results. Also tried:

<img class="pic left" src='<%= image_path "#{@page.image}" %>' />  

still get routing error, but only looking in "/images" directory. I am still in development mode, so I thought that image_path would be the correct path.

What is the correct way of accessing an image, that was just uploaded to a directory outside of the asset pipeline? That will work in development or production env? I really thought this would be straight forward.

Rails 4 after_commit nested conditions issue

Posted: 30 Dec 2016 04:34 AM PST

I would like to trigger the same function for after_commit on both update and create BUT I would like to apply a particular condition only for update.

For now, my only solution was to duplicate the function and make two different after_commit like this:

after_commit :my_method_on_update,                 on: :update,                 if: ->(foo) { foo.previous_changes.key?(:bar) }    after_commit :my_method_on_destroy, on: :destroy    def my_method_on_update    # stuff  end    def my_method_on_destroy    # same stuff here  end  

Of course it works but it doesn't make the code DRY at all. I'm sure there is a better solution but I haven't found any relevant examples on the official rails doc

What I'd like is something like this:

after_commit :my_method,                 on: :update,                 if: ->(foo) { foo.previous_changes.key?(:bar) },                 on: destroy    def my_method    # stuff  end  

But there is an error with twice the declaration of on.

Active Admin Installation Error

Posted: 30 Dec 2016 04:41 AM PST

I created a sample application in RubyonRails and tried to use Active Admin gem.

Added the below lines to Gem file:

gem 'activeadmin'  gem 'sass-rails'  gem "meta_search", '>= 1.1.0.pre'  

Then ran the following command rails generate active_admin:install but got the below error:

Running via Spring preloader in process 1726  Expected string default value for '--jbuilder'; got true (boolean)  Expected string default value for '--helper'; got true (boolean)  Expected string default value for '--assets'; got true (boolean)  Could not find generator 'active_admin:install'. Maybe you meant 'active_record:model', 'active_record:migration' or 'integration_test'  Run `rails generate --help` for more options.  

what configuration do i need for actionmailer to work in cloud9?

Posted: 30 Dec 2016 02:25 AM PST

I have been following this simple tutorial for sending mail using ActionMailer.

http://guides.rubyonrails.org/action_mailer_basics.html

The configuration i am using in development.rb file is as follows:

  config.action_mailer.delivery_method = :smtp          config.action_mailer.smtp_settings = {            :address => 'smtp.mailgun.org',        :domain => 'sandbox1b1a6a9b09cb4df4b1e7489ad0747f6d.mailgun.org',        :port => 587,        :user_name => 'postmaster@sandbox1b1a6a9b09cb4df4b1e7489ad0747f6d.mailgun.org',        :password => 'validpassword',        :authentication => 'plain'            }        config.action_mailer.raise_delivery_errors = true        config.action_mailer.perform_deliveries = true  

I have also tested with gmail smtp but with no success. The above configuration is for mailgun smtp.

I send email through the terminal and the following message is printed in console. But the email is never received by the recipient. I am doubtful whether i have missed an important configuration for cloud 9 that is not letting me send emails. I appreciate any help! Thanks!

ExampleMailer#sample_email: processed outbound mail in 281.6ms  Sent mail to validemail@gmail.com (30015.9ms)  Date: Fri, 30 Dec 2016 10:20:48 +0000  From: fromemail@gmail.com  To: validemail@gmail.com  Message-ID: <58663500a6530_e5adab0d8803a3@kofhearts-rubyonrails-3267120.mail>  Subject: Sample Email  Mime-Version: 1.0  Content-Type: multipart/alternative;   boundary="--==_mimepart_58663500a41fe_e5adab0d8802e9";   charset=UTF-8  Content-Transfer-Encoding: 7bit      ----==_mimepart_58663500a41fe_e5adab0d8802e9  Content-Type: text/plain;   charset=UTF-8  Content-Transfer-Encoding: 7bit    Hi hello  Sample mail sent using smtp.    ----==_mimepart_58663500a41fe_e5adab0d8802e9  Content-Type: text/html;   charset=UTF-8  Content-Transfer-Encoding: 7bit    <!DOCTYPE html>  <html>    <head>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />      <style>        /* Email styles need to be inline */      </style>    </head>      <body>      <!DOCTYPE html>  <html>    <head>      <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />    </head>    <body>      <h1>Hi dog</h1>      <p>        Sample mail sent using smtp.      </p>    </body>  </html>    </body>  </html>    ----==_mimepart_58663500a41fe_e5adab0d8802e9--  

How to use "has_many through" model in form of active admin

Posted: 30 Dec 2016 02:02 AM PST

So i have model "ClientHotel", "ConferenceRoom", "Slot" and associations between these is like

class Slot < ActiveRecord::Base   belongs_to :conference_room   belongs_to :client_hotel   has_many :bookings  end    class ConferenceRoom < ActiveRecord::Base    belongs_to :client_hotel    has_many :slots    accepts_nested_attributes_for :slots, allow_destroy: true  end    class ClientHotel < ActiveRecord::Base      has_many :slots, through: :conference_rooms    has_many :conference_rooms    has_many :bookings    has_many :holidays    accepts_nested_attributes_for :conference_rooms, allow_destroy: true    accepts_nested_attributes_for :slots, allow_destroy: true  end  

and this is my file in app/admin/client_hotel.rb

ActiveAdmin.register ClientHotel do    permit_params :hotel_name, :email, :password, :password_confirmation     form do |f|     f.inputs do      f.input :hotel_name      f.input :email      f.input :password      f.input :password_confirmation      f.has_many :conference_rooms do |pd|        pd.semantic_errors *pd.object.errors.keys        pd.input :name  

here how to add the slots attributes so that while creating the hotel i should be able to create the conf_room and slot also in one go.

    end    end   f.submit  end    show do    attributes_table do      row :hotel_name      row :email    end  end  end  

suppose i have check-in time & checkout time in slots table so how would i write that in above form

How to save attachment locally using trix editor

Posted: 30 Dec 2016 01:17 AM PST

In ruby on rails, how to save attachment to folder using basecamp's trix html editor

   document.addEventListener("trix-initialize", function(event) {          Trix.Inspector.install(event.target);      });        document.addEventListener("trix-attachment-add", function(event) {          var attachment = event.attachment;          if (attachment.file) {              var xhr = new XMLHttpRequest;              xhr.open("POST", "/img", true);                xhr.upload.onprogress = function(event) {                  var progress = event.loaded / event.total * 100;                  attachment.setUploadProgress(progress);              };                xhr.onload = function() {                  if (xhr.status === 201) {                      setTimeout(function() {                          var url = xhr.responseText;                          attachment.setAttributes({ url: url, href: url });                      }, 30)                  }              };                attachment.setUploadProgress(10);                setTimeout(function() {                  xhr.send(attachment.file);              }, 30)          }      });  

I got this error: POST http://localhost:3000/img 404 (Not Found)