Saturday, May 28, 2016

RoR: Param is missing or the value is empty | Fixed issues

RoR: Param is missing or the value is empty | Fixed issues


RoR: Param is missing or the value is empty

Posted: 28 May 2016 06:45 AM PDT

I am getting an error when I try to update a prop(which is like an article). I can create a prop but when I go to edit it I get the following error:

enter image description here

This is my props controller:

class PropsController < ApplicationController attr_accessor :user, :answer, :choice, :prop

  def index      @props=Prop.all    end      def show      @prop = Prop.find(params[:id])    end      def new      @prop = Prop.new      @user = User.find(session[:user_id])      end      def edit      @prop = Prop.find(params[:id])      @user = User.find(session[:user_id])      @answer = @user.answers.update(prop_params)        end      def create      @prop = Prop.new(prop_params)      @user = User.find(session[:user_id])        @answer = Answer.new        if @prop.save      redirect_to @prop      else      render 'new'      end      end      def update      @user = User.find(session[:user_id])        @prop = Prop.find(params[:prop_id])      @answer = @user.answers.update(answer_params)        if @prop.update(prop_params)        redirect_to @prop      else        render 'edit'      end        if @answer.choice == @prop.choice        puts "hello"        @user.score += 7        @user.save      else        @user.score -= 7        @user.save        end    end      def destroy      @prop = Prop.find(params[:id])      @prop.destroy        redirect_to props_path    end      def select      @prop = Prop.find(params[:choice])    end    end    private    def prop_params      params.require(:prop).permit(:title, :text, :choice, :user_id, :id)    end      def answer_params      params.require(:answer).permit(:choice, :id, :prop_id, :user_id)    end  

This is my form. It is a partials shared between the new and edit views:

<%= form_for @prop do |f| %>      <% if @prop.errors.any? %>      <div class="error_explanation">        <h2>          <%= pluralize(@prop.errors.count, "error")  %>  prohibited this prop from being saved:        </h2>        <ul>          <% @prop.errors.full_messages.each do |msg|  %>          <li><%= msg  %></li>          <% end %>        </ul>      </div>    <% end %>        <p>      <%= f.label :title %><br>      <%= f.text_field :title %>    </p>      <p>      <%= f.label :text %><br>      <%= f.text_area :text %>    </p>        <%= f.radio_button(:choice, "A") %>    <%= f.label(:choice, "The Correct Answer is A") %>    <%= f.radio_button(:choice, "B") %>    <%= f.label(:choice, "The Correct Answer is B") %>    <%= f.radio_button(:choice, "C") %>    <%= f.label(:choice, "The Answer Has Yet To Be Determined") %>    <%= f.hidden_field :user_id, :value => @user.id %>        <p>      <%= f.submit %>    </p>  <% end %>  

OR clause in Rails 5

Posted: 28 May 2016 06:59 AM PDT

How can I get (A || B) && ( C || D) query in Rails 5 ActiveRecord?. I tried Post.where(a).or(Post.where(b)).where(c).or(Post.where(d))

but It produces as: (A || B) && C || D. What would be the correct code to get desired query?

Rails - Database Translation static values

Posted: 28 May 2016 06:29 AM PDT

I have a model called house. In this model I have some amenities such as Wi-fi, Tv, air conditioning etc. These are basically in english and checkbox. User clicks them and I show them on home#show page with disabled class as; <%= @home.amenities.each do |amenity| %> ....

The thing is users can select language with locale variable so that the web site turns in to french for instance. For the static texts, flash and error messages I was able translate and works just fine.

But I do not know how should I translate these model based values. The website looks like frenglish right now.

Every server log line suddenly prepended with timestamp

Posted: 28 May 2016 06:00 AM PDT

I'm on Rails 5 (5.0.0.rc1) and Puma as server.

I don't know exactly when this started, but the server logs look like this right now:

I, [2016-05-28T14:54:24.618182 #1326] INFO -- : Parameters: {"index"=>"latest", "token"=>"-OnCaEehp0oXrbTeWRszASD7WLtaNfgcUp_lh3s1ISSFR1UA3Z1x379Ptp51rn9yoVJQKQErgZhtDVkC4kBk6w"}
D, [2016-05-28T14:53:59.968296 #1325] DEBUG -- : CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 271], ["LIMIT", 1]]

The part of every line until "-- :" is new to me. Where does this prepending come from and how do I suppress it?

Best use of content_tag in a custom link_to helper method

Posted: 28 May 2016 05:28 AM PDT

What is the best way to use a custom helper method in order to generate html tags with links and html options?

lets say

def drop_document_options(title,document,version,html_options)      end  

in order to generate a link with the parameters:

<div class="dropdown">  <button class="btn btn-default btn-sm dropdown-toggle" type="button" data-toggle="dropdown">    <%=@hebrew_document[document]%>  - <%=@hebrew_version[version]%>    <span class="caret"></span></button>    <ul class="dropdown-menu dropdown-menu-right">      <li> <%=link_to( {:controller => "invoices",                        :action => "download",                        :id => document.id,                        :disposition => 'inline',                        :version => version[i]} ,                        html_options )  do %>                          <%=action_title%>      <% end %>       </li>    </ul>  </div>  

saving an object value passed by function

Posted: 28 May 2016 05:50 AM PDT

I have the folliwing code:

class LogFactory < ActiveRecord::Base     after_initialize :inizializza     MESSAGENOTDEFINED = "Msg"         def inizializza        self.happened = Time.current        self.messaggio = MESSAGENOTDEFINED     end            def setMessage(messaggio)          logger = LogFactory.new(:messaggio => messaggio, :happened => self.happened)          logger.save      end     end  

The problem is in the messaggio variable. I mean, even if i use the param messaggio in the .new(:messaggio => messaggio,.. rails still use the MESSAGENOTDEFINED constant defined during the initialization. Why?

Preventing ActionView::MissingTemplate in a Backend-only (API) application?

Posted: 28 May 2016 04:47 AM PDT

My backend API-only application is responding to clients with a RestClient::InternalServerError: 500 Internal Server Error because of the following code ( and there being no templates to render ).

def create      @project = Project.create(params.require(:project).permit(:name))      @project.update_attributes(key: Devise.friendly_token)        respond_to do |format|          format.html          format.json { render json: @project }      end  end  

Current Solution:

Based on the Rails guide to Layouts and Rendering, this can be prevented by using render json: @project

Source: http://guides.rubyonrails.org/layouts_and_rendering.html

The Ask:

But I want to give the client the option of format, so the respond_to block is the more ideal choice.

Is there a way to combine these to use the first block but not result in a 500 error?

Thanks kindly.

Rails :: Generate slugs with FriendlyId, Globalize and slug_candidates

Posted: 28 May 2016 04:36 AM PDT

I am building a Rails application and I am stuck when generating slug for an article with the second locale defined.
For the main locale (french), it checked if an article already have the title and if it's the case add an integer (id) at the end but for the second locale (english) it's just generate the slug without checking if article exists (which give me duplicated slugs).

Here is my model:

class Post < ActiveRecord::Base    translates :title, :slug, :content, fallbacks_for_empty_translations: true     active_admin_translates :title, :slug, :content, fallbacks_for_empty_translations: true       extend FriendlyId     friendly_id :slug_candidates, use: [:slugged, :globalize, :finders]      private      def slug_candidates      [:title, [:title, :deduced_id]] # works for main locale but not others    end      def deduced_id      self.class.where(title: title).count + 1    end  end  

How can I get the id added to slug for secondary locales when article already exists with same title ?

Thanks for your help !

My Project:

  • Rails 4.2.6
  • ActiveAdmin 1.0.0.pre2
  • Globalize 5.0.1
  • FriendlyId 5.1.0
  • FriendlyId-globalize 1.0.0.alpha2

returning nokogiri webscrape as json

Posted: 28 May 2016 06:16 AM PDT

I've this bit of code.

require 'rubygems'  require 'nokogiri'  require 'open-uri'  namespace :task do    task test: :environment do      ticketmaster_url = "http://www.ticketmaster.co.uk/derren-brown-miracle-glasgow-04-07-2016/event/370050789149169E?artistid=1408737&majorcatid=10002&minorcatid=53&tpab=-1"      doc = Nokogiri::HTML(open( ticketmaster_url ))      event_name = nil      ticket_price = nil      doc.xpath("//script[@type='text/javascript']/text()").each do |text|        if text.content =~ /TM\.Tracking\.satellite/          event_name = text.content[/"eventName":".*?"/].gsub!('"eventName":', '').gsub!('"', '')        elsif text.content =~ /more_options_on_polling/          ticket_price = text.content[/"total_price":"\d+\.\d+"/].gsub!('"total_price":', '').gsub!('"', '').to_f        end      end  byebug      puts "Event name: " + event_name      puts "Ticket price: " + ticket_price.to_s    end  end  

Now i've noticed that via the view page source i can see that there is this:

event: new TMEvent({"event_id":"370050789149169E","date":"Mon  4 Jul 2016, 19:30","suppress_best_available":"","sorted_ticket_types":["000000000001","000000000005"],  

I've copied all of it intot he json formatter and realised its json ^_^

How would i be able to move this into json so that i can utilise it better. (i absolutely hate the method its done at the moment,I can't understand regex very well!)

ideally what im wanting is for the code to pass back everything inside the "secnames2tickettypes" (i believe so far)

Thanks Sam

error during signin in authentication_pages_spec

Posted: 28 May 2016 06:25 AM PDT

Fllowing the Michael hartl tutorial i'm getting the following error "undefined method pages" in authentication_pages_spec during sign in Chapter 8.

first image

enter image description here

authentication_pages_spec.rb

require 'rails_helper'    RSpec.describe "AuthenticationPages", type: :request do      subject { pages }        describe "signin pages" do          before { visit signin_path }            it { should have_selector('h1', text: 'Sign in')}          it { should have_selector('title', text: 'Sign in')}      end        describe "signin" do          before { visit signin_path }            describe "with invalid information" do              before { click_button "Sign in" }                it { should have_selector('title', text: 'Sign in')}              it { should have_selector('div.alert.alert-error', text: 'Invalid')}          describe "after visiting another page" do            before { click_link "Home" }            it { should_not have_selector('div.alert.alert-error') }        end          end            describe "with valid information" do              let(:user) {FactoryGirl.create(:user)}              before do                  fill_in "Email", with: user.email                  fill_in "Password", with: user.password                  click_button "Sign in"              end                it { should have_selector('title', text: user.name) }              it { should have_link('Profile', href: user_path(user))}              it { should have_link('Sign out', href: signout_path)}              it { should_not have_link('Sign in', href: signin_path)}          end      end  end  

new.html.erb

<% provide(:title, "Sign in") %>  <h1>Sign in</h1>    <div class = "row">      <div class = "col-md-6 col-md-offset-3">          <%= form_for(:session, url: sessions_path) do |f| %>                <%= f.label :email %>              <%= f.text_field :email %>                <%= f.label :password %>              <%= f.password_field :password %>                <%= f.submit "Sign in", class: "btn btn-large btn-primary" %>                <p> New user? <%= link_to "Sign up now", signup_path %></p>            <% end %>      </div>  </div>  

routes.rb

Rails.application.routes.draw do    resources :users    resources :sessions, only: [:new, :create, :destroy]      root to: 'static_pages#home'    get '/signup', to: 'users#new'    get '/signin', to: 'sessions#new'    get '/signout', to: 'sessions#destroy', via: :delete    get '/help', to: 'static_pages#help'    get '/about', to: 'static_pages#about'    resources :users  end  

Session_controller.rb

class SessionsController < ApplicationController        def new      end        def create          user = User.find_by_email(params[:session][:email])          if user && user.authennticate(params[:session][:password])              #Sign the user in a redirect to the user's show page.          else              #Create an error message and re-render the signin form              flash.now[:error] = 'Invalid email/password combination'              render 'new'          end      end        def destroy      end    end  

Best way to handle 2 different log in types for Devise? (email/password or fb_id/access_token)

Posted: 28 May 2016 04:06 AM PDT

I am creating a JSON only api. I want mobile to be able to signup/signin either with email/password or fb_id/access_token

The issue is Devise is setup to handle email/password, so I feed like I'm constantly fighting to get Facebook to work.

Omniauth-facebook gem doesn't help, because instead of getting the data from a Facebook redirect. The client posts to /user with either {email: "email", password: "password"} or {fb_id: "123", access_token: "456"}

Here is my current registration controller:

module DeviseTokenAuth    class RegistrationsController < DeviseTokenAuth::ApplicationController      before_action :set_user_by_token, :only => [:destroy, :update]      before_action :validate_sign_up_params, :only => :create      before_action :validate_account_update_params, :only => :update      skip_after_action :update_auth_header, :only => [:create, :destroy]        def create        if params[:email].present? and params[:password].present? and params[:password_confirmation].present?          create_from_email        elsif params[:fb_id].present? and params[:access_token].present?          create_from_facebook        end      end        def create_from_email        @resource            = resource_class.new(sign_up_params)        @resource.provider   = "email"          if resource_class.case_insensitive_keys.include?(:email)          @resource.email = sign_up_params[:email].try :downcase        else          @resource.email = sign_up_params[:email]        end          finish_create      end        def create_from_facebook        @resource = User.from_facebook(sign_up_params[:fb_id], sign_up_params[:access_token])          finish_create      end          def finish_create          ### Standard devise_token_auth #create action      end    end  end  

User Model

def self.from_facebook(fb_id, access_token)      facebook_data = HTTParty.get("https://graph.facebook.com/me", query: {        access_token: access_token,        fields: "email,id,picture,name"      }).parsed_response        User.new({        email: facebook_data.try(:[], "email"),        name: facebook_data.try(:[], "name"),        fb_id: facebook_data.try(:[], "id"),        uid: facebook_data.try(:[], "id"),        provider: "facebook",        password: SecureRandom.hex(5),        image: facebook_data.try(:[], "picture").try(:[], "data").try(:[], "url")      })    end  

Installing Rails on Mac OS X El Capitan v10.11.1

Posted: 28 May 2016 05:48 AM PDT

ERROR: While executing gem ... (Gem::RemoteFetcher::FetchError) Errno::ECONNRESET: Connection reset by peer - SSL_connect (https://api.rubygems.org/quick/Marshal.4.8/loofah-2.0.3.gemspec.rz)

^Keep getting the above. Note I'm in China and have tried both with/without VPN. Have also gone to https://ruby.taobao.org/ but do not know how to install this.

How edit job in sidekiq queue?

Posted: 28 May 2016 03:27 AM PDT

I have a queue that happened to contain wrong parameters for the perform_async worker. I don't want to loose the jobs, but edit arguments so they will succeed next time or on forced retry.

Is this possible?

How to organize Rails app where each customer has it's own specific gem list?

Posted: 28 May 2016 03:49 AM PDT

I'm creating an architecture of the app and trying to find the best one. Few words about it:

  • Box solution (each app installed on customer's machine)
  • There is a Main app and gems to extend it (private)
  • Main app has default list of gem
  • Other functionality extending by adding additional gems by request (our gems)

But some customers no need full functionality, so we don't need to include all gems to it's Gemfile.

What is the best way to organize it? What do you think about this way? Maybe you can offer more effective way?

Rails 4 - post completion evaluations model - structure

Posted: 28 May 2016 03:12 AM PDT

I'm still feeling my way with Rails.

I'm trying to add an evaluation function to my projects based app.

I want each project participant to submit an evaluation when a project is complete.

I have an evaluation model with:

Evaluation.rb

# == Schema Information  #  # Table name: evaluations  #  #  id                :integer          not null, primary key  #  user_id           :integer  #  evaluatable_id    :integer  #  evaluatable_type  :string  #  overall_score     :integer  #  project_score     :integer  #  personal_score    :integer  #  remark            :text  #  work_again?       :boolean  #  continue_project? :boolean  #  created_at        :datetime         not null  #  updated_at        :datetime         not null  #  # Indexes  #  #  index_evaluations_on_evaluatable_type_and_evaluatable_id  (evaluatable_type,evaluatable_id) UNIQUE  #    class Evaluation < ActiveRecord::Base      # --------------- associations      belongs_to :evaluator, :polymorphic => true, class_name: 'Evaluation'    belongs_to :evaluatable, :polymorphic => true, class_name: 'Evaluation'        # --------------- scopes      # --------------- validations      # --------------- class methods      # --------------- callbacks      # --------------- instance methods      # --------------- private methods    end  

I have concerns for:

module Evaluatable      extend ActiveSupport::Concern        included do           has_many :received_evaluations, as: :evaluatable, dependent: :destroy, class_name: 'Evaluation'      end  end    module Evaluator      extend ActiveSupport::Concern        included do           has_many :given_evaluations, as: :evaluator, dependent: :destroy, class_name: 'Evaluation'        end  end  

I'm then trying to show each user's evaluations (received) as:

<% Evaluation.find(params[:id]).evaluation.order('created_at DESC').each do |eval| %>                                  <div id="portfolioFiltering" class="masonry-wrapper row">                                          <%= eval.remark %>                                          <%= eval.personal_score %>                                          <small><%= eval.created_at %></small>                                  </div>                                  <% end %>    

But I get this error:

undefined method `evaluations' for #<Evaluation:0x007ff274b13b90>  Did you mean?  evaluator                 evaluator=  

I'm not even sure I've understood the error message, let alone figured out what to do about it.

Can anyone make sense of this message?

Multiple database records with one form?

Posted: 28 May 2016 01:17 AM PDT

I am currently creating a survey where the user is able to choose from four different options for every category. For example:

Category 1: [X] Option 1 – [] Option 2 – [] Option 3 – [] Option 4

What I have so far is a table with categories. There I have the names of the categories and some extra info for each category.

Additionally I have a survey controller with the form where every category with the options is listed (eaches through the category table entries). The survey table holds the value (option 1, 2, 3 or 4), the category_id as well as the user_id. What I want to achieve now is that it creates multiple database records in the survey table for each category the user fills out basically with one form (?).

I had the idea to each through the categories and have the form within the each, the problem is that I will have 25 different forms and every form has its own submit button. I could fiddle around with JS and hide every button expect the last but that seems like a bad idea.

What would be the best solution for the problem I am facing?

Thanks for any help!

How to send email confirmation using gem devise&mailgun

Posted: 28 May 2016 01:23 AM PDT

I am having troubles with sending email confirmation using devise and mailgun. I have installed devise and changed setting to send email but whenever I signup as a newcomer there is no confirmation email sent. Can anyone specifically explain how to do it? Thanks.

config/environments/developments.rb

How to config Grape API time zone per request

Posted: 28 May 2016 12:50 AM PDT

I want to manage multi time zone, in my Grape API, is there a way to add around filter to set the current user's time zone? like this in Rails

around_filter :set_time_zone

    def set_time_zone        old_time_zone = Time.zone        Time.zone = current_user.time_zone if logged_in?        yield      ensure        Time.zone = old_time_zone      end  

Iterating through an array, adding occurrances of a true

Posted: 28 May 2016 03:08 AM PDT

I've Been looking around a bit but unsure i'm searching for the right thing.

Say i have this

array ['f', 't', 'f', 't', 't', 't', 'f', 'f', 't', 't', 't', 't', 't', 't', 'f', 't']  

(I have an array of true/false in postgresql which i've used to import to javascript, and it's come back as 't's and 'f's)

I'm looking to change that array to

[1, 3, 6, 1] (adding all the trues in between false)  

Assuming there's some sort of super obvious way I've completely missed!

How to prevent the race condition in this simple example?

Posted: 28 May 2016 12:46 AM PDT

The code below will fetch a new address from an external API if the user doesn't yet have one:

  def create_address        if current_user.address.blank?        data = AddressAPI.create_address        current_user.update!(address: data['address'])      end        render json: { address: current_user.address }    end  

If two concurrent create_address requests come in, it's possible they'll both pass the current_user.address.blank? check and two addresses will be created (whatever will call update! last will override the other one).

How do we prevent this? Do we need to use some sort of locking mechanism?

How to make JSSOR Slider fit to screen width while keeping the aspect ratio?

Posted: 27 May 2016 11:51 PM PDT

I'm trying to create an automatic slideshow for my website. I used the JSSOR slider, which works pretty nice. However, it requires you to provide the height and the width of the slider in exact pixels(e.g. 60px or 140px, but not 100% or auto).

I want this slider to fit to the screen width, and the height should be scaled while protecting the aspect ratio.

I tried to dynamically(in JS) specify the width and height of the slider, but it didn't work.

Any suggestions? Here is the html code; (Yes, it is in rails)

<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 1340px; height: 768px; ">  <!-- Slides Container -->  <div id="slides_div" u="slides" style="position: absolute; overflow: hidden; left: 0px; top: 0px; width: 1340px; height: 768px; ">      <div><%= image_tag "slider2.jpg", class: "landing-row" %></div>      <div><%= image_tag "slider3.jpg", class: "landing-row" %></div>      <div><%= image_tag "slider4.jpg", class: "landing-row" %></div>      <div><%= image_tag "slider5.jpg", class: "landing-row" %></div>      <div><%= image_tag "slider6.jpg", class: "landing-row" %></div>      <div><%= image_tag "slider7.jpg", class: "landing-row" %></div>  </div>  

And here is the JS code;

jQuery(document).ready(function ($) {      var options = { $AutoPlay: true, $SlideDuration: 750, $Idle: 5000, $DragOrientation: 0};      var jssor_slider1 = new $JssorSlider$('slider1_container', options);  });  

Thanks.

Why Angular doesn't work when including it using Rails asset pipeline?

Posted: 28 May 2016 02:51 AM PDT

I have js controller where Factory is called:

(function() {    'use strict';    angular      .module('projectAlabama')        .controller('indexResourceListController', indexResourceListController);      indexResourceListController.$inject = ['resourceListFactory'];      function indexResourceListController(resourceListFactory) {      var vm = this;        resourceListFactory.query().$promise.then(function(data) {        vm.lists = data.splice(0, limit);      });    }  })();  

2 approaches of including angular into the project - different result.

First one: using asset pipeline

Gemfile

source 'https://rails-assets.org'  gem 'rails-assets-angular'  gem 'rails-assets-ng-resource'  

application.js

//= require angular  //= require ng-resource  //= require angular-route  //= require angular-rails-templates  //= require angular-material    //= require app  //= require_tree ./templates  //= require_tree ./controllers  //= require_tree ./factories  

Error !

angular.self.js?body=1:13643 TypeError: Cannot read property 'then' of undefined  at new indexResourceListController  

Second approach using CDN:

layout.html.erb

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-resource.min.js"></script>  

And everything works smoothly.

Can someone explain me why ?

Setup resque / redis on separate server

Posted: 27 May 2016 11:04 PM PDT

I am splitting my redis and resque workers out to a new machine. Previously they all ran on one machine - successfully.

I us cap for deploying and after a successful deploy I get this in my rails log when I try to queue up a resque job:

==> shared/log/production.log <==  I, [2016-05-28T05:43:03.924222 #5769]  INFO -- : Started GET "/photos/24803/rotate/180" for 127.0.0.1 at 2016-05-28 05:43:03 +0000  I, [2016-05-28T05:43:04.080861 #5769]  INFO -- : Processing by PhotosController#rotate as HTML  I, [2016-05-28T05:43:04.081274 #5769]  INFO -- :   Parameters: {"id"=>"24803", "degrees"=>"180"}  D, [2016-05-28T05:43:04.183430 #5769] DEBUG -- :   Photo Load (1.4ms)  SELECT  `photos`.* FROM `photos` WHERE `photos`.`id` = 24803 LIMIT 1  I, [2016-05-28T05:43:04.250844 #5769]  INFO -- : Completed 500 Internal Server Error in 169ms (ActiveRecord: 22.1ms)  F, [2016-05-28T05:43:04.256268 #5769] FATAL -- :   Redis::CannotConnectError (Error connecting to Redis on localhost:6379 (Errno::ECONNREFUSED)):    app/models/photo.rb:109:in `rotate'    app/controllers/photos_controller.rb:106:in `rotate'  

So I'm thinking that my app server does not get that it should go to the "backend server" for this stuff.

My configuration:

I have the app server running op 192.168.2.102 - everything is installed there except for redis. Redis is installed on 192.168.2.103

config/deploy.rb:

server '192.168.2.102', port: 22, roles: [:web, :app], primary: true  server '192.168.2.103', port: 22, roles: [:db, :resque_worker, :resque_scheduler]      set :repo_url,        'xxx'  set :application,     'xxx'  set :user,            'deploy'  set :puma_threads,    [4, 16]  set :puma_workers,    0  set :workers, { "import" => 1, "utility" => 1 }  set :resque_environment_task, true    # 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) }  set :puma_preload_app, true  set :puma_worker_timeout, nil  set :puma_init_active_record, true  # Change to false when not using ActiveRecord    ## Defaults:  set :scm,           :git  set :branch,        :master  # set :format,        :pretty  # set :log_level,     :debug  # set :keep_releases, 5    ## Linked Files & Directories (Default None):  #set :linked_files, %w{db/production.sqlite3}  set :linked_dirs,  %w{ log tmp/pids tmp/cache tmp/sockets public/system }  #set :bundle_binstubs, nil    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,    :compile_assets    after  :finishing,    :cleanup    after  :finishing,    :restart          end  after "deploy:restart", "resque:restart"  # ps aux | grep puma    # Get puma pid  # kill -s SIGUSR2 pid   # Restart puma  # kill -s SIGTERM pid   # Stop puma  

config/resque.yml:

development: localhost:6379  test: localhost:6379  production: 192.168.2.103:6379  

config/initializers/resque.rb

rails_root = ENV['RAILS_ROOT'] || File.dirname(__FILE__) + '/../..'  rails_env = ENV['RAILS_ENV'] || 'development'    resque_config = YAML.load_file(rails_root + '/config/resque.yml')  Resque.redis = resque_config[rails_env]    Resque.logger = MonoLogger.new(File.open("#{Rails.root}/log/resque.log", "w+"))  Resque.logger.formatter = Resque::QuietFormatter.new  

config/initializers/redis.rb:

$redis = Redis.new(:host => ENV["REDIS_HOST"], :port => ENV["REDIS_PORT"])  

I'not sure whether I need the last file...

If you're thinking that it's my connectio setup that's wrong then think no more (about that..). Firstly Resque is not even trying to connect to the right redis. secondly, when I do this:

...on 192.168.2.103:

deploy@raspberrypi:~/apps/phototank $ netstat -nlpt | grep 6379  (Not all processes could be identified, non-owned process info   will not be shown, you would have to be root to see it all.)  tcp        0      0 0.0.0.0:6379            0.0.0.0:*               LISTEN      -                 tcp6       0      0 :::6379                 :::*                    LISTEN      -    

...on 192.168.2.102:

deploy@raspberrypi:~/apps/phototank $ redis-cli -h 192.168.2.103 ping  PONG  

bundle package with rvm

Posted: 27 May 2016 10:46 PM PDT

I was reading the book Rails Way. And it discusses running "bundle package". This will store all the .gem files your app uses in vendor/cache. Running bundle install will prefer gems in vendor/cache to gems in other locations. I am using rvm, so I tested this with rvm:

rvm gemset create rent_prototype  rvm use 2.2.1@rent_prototype  gem install rails  rvm gemdir  /home/viggy/.rvm/gems/ruby-2.2.1@rentme_prototype  $ cd /home/viggy/.rvm/gems/ruby-2.2.1@rentme_prototype  $ ls -l devise-4.1.1  ls: cannot access devise-4.1.1: No such file or directory  

Above I created a gemset with rvm and checked if the devise gem was installed, and it was not since it is not in Gemfile. Now I use bundle package:

$ cd -  $ bundle package    Updating files in vendor/cache    * rake-11.1.2.gem    * i18n-0.7.0.gem    * json-1.8.3.gem    ...  $ cd vendor/cache  $ ls -l devise-4.1.1  ls: cannot access devise-4.1.1: No such file or directory  

Of course, no devise gem in vendor/cache either.

Then I modify Gemfile and add:

gem 'devise'  

Then I run bundle install.

Now I check where devise was installed:

$ bundle show devise  /home/viggy/.rvm/gems/ruby-2.2.1@rentme_prototype/gems/devise-4.1.1  $ cd vendor/cache  $ ls -l devise-4.1.1  ls: cannot access devise-4.1.1: No such file or directory  

So when I install a gem, it installs in the rvm folder. It does not prefer vendor/cache to other locations. If that is the case, what is the purpose of "bundle package" when you are using rvm?

PG::UndefindColumn: ERROR on only at action test

Posted: 28 May 2016 12:53 AM PDT

I'm getting this test error when I run my test by "bundle exec rake test"

ERROR["test_unsuccessful_edit", UsersEditTest... ActionView::Template::Error: ActionView::Template::Error: PG::UndefinedColumn: ERROR: column groups_users.group_id does not exist

It works fine on development. My test script is below.

# test "unsuccessful edit" do  #   log_in_as(@user)  #   get edit_user_path(@user)  #   assert_template 'users/edit'  #   patch user_path(@user), user: { name: "",  #   email: "foo@invalid",  #   password: "foo",  #   password_confirmation: "bar",  #  }  #   assert_template 'users/edit'  # end  

As you can see, I skipped this test since it apparently nothing wrong in the development environment.

The error message is saying "group_id" column does not exist in table "groups_users". But it's actually exist since I've run migration and checked database/behavior by hands.

Is there any way to make this test script work?

In my models, as you may be guessing, I have below relationships method.

• User.rb

  has_and_belongs_to_many :groups, join_table: :groups_users, dependent: :destroy  

• Group.rb

  has_and_belongs_to_many :user, join_table: :groups_users  

And my migration file looks like this:

class GroupsUsers < ActiveRecord::Migration    def change      create_table :groups_users, :id => false do |t|          t.integer :group_id          t.integer :user_id      end    end  end  

There is no validation for these groups values to be present. Please let me know if you have any idea or questions.

Thanks,

Allow customer to set up his BrainTree Account in My Rails App

Posted: 27 May 2016 09:57 PM PDT

I am working on this app where i have users and the user can set up payment gateway of his choice from which he wants his (user's) customers to pay while checking out. I have got to implement BrainTree and have no idea how to do it.

I have to ask the user to enter his public key, private key and his merchant id in my app and that would set up his payment gateway. I'm not sure i'm very clear and i'm also clueless as to search what exactly and with what to start.

Please guide me in the right direction. Also do comment if its not clear. Any sort of help will be appreciated.

P.S: Just so that this is clear. My user has his customers and he will enter his braintree account details so that braintree is his payment gateway.

Ruby convert hash to histogram in csv

Posted: 28 May 2016 04:03 AM PDT

I have a hash that looks like this:

@histogram = {    "Date 1" => [       {"Item 1" => 1},       {"Item 4" => 3}    ],    "Date 2" => [       {"Item 2" => 7},       {"Item 1" => 2},       {"Item 5" => 1}    ],    "Date 3" => [       {"Item 4" => 3},       {"Item 2" => 2},       {"Item 8" => 1},       {"Item 1" => 5}    ]  }  

I want to convert that into a day by day histogram CSV file that looks like this:

|        | Date 1 | Date 2 | Date 3 |  | Item 1 |   1    |   2    |   5    |  | Item 2 |        |   7    |   2    |  | Item 4 |   3    |        |   3    |  | Item 5 |        |   1    |        |  | Item 8 |        |        |   8    |  

What's tripping me up is the fact that the @histogram hash can be totally out of order. The dates (keys) are likely to be in order, but the Items are going to be totally out of order. Moreover, as you can see, the items don't have to be the same across different dates. Where an item is not existent on a particular date, it's quantity in the histogram can be assumed to be 0.

Friendly_id and globalize gem conflict

Posted: 27 May 2016 09:09 PM PDT

I am using Friendly_id and globalize gem. I am using :company_name as Friendly_id in my user table. But When I change :company_name to another language using globalize, I encountered ActiveRecord::RecordNotFound

split one big table to multi tables

Posted: 28 May 2016 01:51 AM PDT

rails app, I have a table, the data already has hundreds of millions of records, I'm going to split the table to multiple tables, this can speed up the read and write.

I found this gem octopus, but he is a master/slave, I just want to split the big table.

or what can I do when the table too big?

enter image description here

CSS works when on static site, but zero height divs when ported to Rails app

Posted: 27 May 2016 09:06 PM PDT

I've been working on porting a static site I built over to a Rails app for learning + extensibility.

The framework is easy enough to understand, asset pipeline is fine, and assets are loading - but for some reason, I'm seeing odd behaviour in my stylesheets between the two.

Expected: http://briansdonohue.com <-- static, just HTML/CSS

Screencap from rails app

Anyway - the stylesheets appear to render the same - except for height. The grid elements are rendering at zero height, rather than filling their parent div like on static.

Static CSS - Github Repo: brianshayne/brianshayne.github.io

Rails SCSS - Github Repo: brianshayne/brianshayne-rails

I'm at a loss as to why it's rendering differently.

No comments:

Post a Comment