Wednesday, April 20, 2016

Ruby on Rails Scope | Fixed issues

Ruby on Rails Scope | Fixed issues


Ruby on Rails Scope

Posted: 20 Apr 2016 07:18 AM PDT

I'm creating a sticker album and I need to scope repeated stickers. I still cant fully understand scopes in rails. So, here is my question. How to get all the repeated stickers from a user.

(!): Figurinha has a 'colada' boolean column, wich means the sticker is placed or not in the album.

User.rb

class User < ActiveRecord::Base    has_many :figurinhas  end  

Figurinha.rb

class Figurinha < ActiveRecord::Base    belongs_to :user    belongs_to :dep      def repetida      coladas = self.user.figurinhas.where(colada: true)      colodas.map{|a| a.dep}.include?(self.dep)    end    end  

Dep.rb

class Dep < ActiveRecord::Base    has_attached_file :avatar    validates_attachment_content_type :avatar, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]      belongs_to :partido, foreign_key: :partido, primary_key: :sigla      def avatar_from_url(url)      self.avatar = open(url)    end  end  

difficulty replicating codepen search bar in rails header

Posted: 20 Apr 2016 07:16 AM PDT

I am trying to implement a responsive search bar in the header of my rails 4.2.4 project.

The particular search bar in question derives from codepen. PEN IS VIEWABLE HERE

codepen HTML

<div class="wrap">     <div class="search">        <input type="text" class="searchTerm" placeholder="What are you looking for?">        <button type="submit" class="searchButton">          <i class="fa fa-search"></i>       </button>     </div>  </div>  

codepen CSS

/*=========================    search bar    ================= */     @import url(https://fonts.googleapis.com/css?family=Open+Sans);     body{     background: #f2f2f1;     font-family: 'Open Sans', sans-serif;   }     .search {     width: 100%;     position: relative   }     .searchTerm {     float: left;     width: 100%;     border: 3px solid #00B4CC;     padding: 5px;     height: 20px;     border-radius: 5px;     outline: none;     color: #9DBFAF;   }     .searchTerm:focus{     color: #00B4CC;   }     .searchButton {     position: absolute;       right: -50px;     width: 40px;     height: 36px;     border: 1px solid #00B4CC;     background: #00B4CC;     text-align: center;     color: #fff;     border-radius: 5px;     cursor: pointer;     font-size: 20px;   }     /*Resize the wrap to see the search bar change!*/     .wrap{     width: 30%;     position: absolute;     top: 50%;     left: 50%;     transform: translate(-50%, -50%);   }  

I followed the usual protocol and copied and coded in the HTML and CSS from the aforementioned pen into my project and also inputed the CDN link into the head.

Note their is no Javascript.

Despite doing so, I cannot get the search bar to resemble how it was intended to look. I have even tried using the most current CDN and that still does not work!.

enter image description here

Any steering would be appreciated.

application.html.erb

<!DOCTYPE html>  <html>  <head>    <title>SampleApp</title>    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => false %>    <%= javascript_include_tag 'application', 'data-turbolinks-track' => false %>    <%= csrf_meta_tags %>    <%= yield :head %>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300,700|Lobster' rel='stylesheet' type='text/css'>    <meta name="viewport" content="width=device-width, initial-scale=1.0">  </head>  <body>        <%= render 'layouts/header' %>      <div class="container">      <% flash.each do |name, msg| %>       <%= content_tag(:div, msg, class: "alert alert-#{name}") %>      <% end %>      <%= yield %>      </div>    <%= render "layouts/footer" %>    </body>  </html>  

_header.html.erb

<nav class="navbar navbar-static-top navbar-default" role="navigation">    <div class="container">    <!-- Brand and toggle get grouped for better mobile display -->    <div class="navbar-header">      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">        <span class="sr-only">Toggle navigation</span>        <span class="icon-bar"></span>        <span class="icon-bar"></span>        <span class="icon-bar"></span>      </button>      <a class="navbar-brand" href="/">        <img alt="Nippon Beauty" class="navbar-brand-icon" src="assets/nippon.svg">      </a>    </div>      <div class="wrap">      <div class="search">        <input type="text" class="searchTerm" placeholder="What are you looking for?">        <button type="submit" class="searchButton">          <i class="fa fa-search"></i>        </button>      </div>    </div>      <!--<span style="color: #53100e">| Japanese and South Korean Luxury Skincare</span>       <!-- Collect the nav links, forms, and other content for toggling -->    <div class="collapse navbar-collapse navbar-ex1-collapse">      <ul class="nav navbar-nav navbar-right">        <li><%= link_to "Home", root_path %></li>        <li><%= link_to "About", about_path %></li>        <li><%= link_to "Login", new_user_session_path %></li>         <li><%= link_to "Signup", new_user_registration_path %></li>        <% if user_signed_in? %>          <li><%= link_to "Account Settings", edit_user_registration_path %></li>          <li><%= link_to "Log out", destroy_user_session_path, method: :delete %></li>        <% else %>      <% end %>      </ul>    </div><!-- /.navbar-collapse -->  </nav>  

bootstrap_and_customization.css.scss

@import url(https://fonts.googleapis.com/css?family=Lato:400,700);    $body-bg:                          #ecf0f1;  $font-family-sans-serif:           'Lato', 'Helvetica Neue', Helvetica, Arial, sans-serif;  $navbar-height:                    70px;  $navbar-default-bg:                white;  $navbar-default-brand-color:       #c0392b;  $brand-primary:                    #c0392b;  $jumbotron-bg:                     white;    @import 'bootstrap';  @import 'bootstrap-sprockets';    .center {       text-align: center;  }    .navbar-brand {       font-weight: bold;  }      .btn-lg {      padding: 18px 28px;      font-size: 22px;      border-radius: 8px;      }      .jumbotron {      width: 735px;      padding-left: 30px;      padding-right: 15px;      padding-bottom: 20px;      padding-top: 20px;  }    .container .jumbotron {      border-radius: 35px;  }      .container {      width: 1270px;  }          .navbar {      min-height: 90px;  }    .navbar-brand {      float: left;      padding: 10px 15px;      font-size: 14px;      font-weight: normal;  }    .navbar-brand img {    display: inline-block;  }      .navbar-brand span {      display:inline-block;      vertical-align : middle;      height: 7px;  }      h1, {    font-family: 'Lobster', cursive;    color: #e22f8f;  }    .row {    position: absolute;    right: 0;    bottom: 0;    left: 0;    padding: 3rem;    background-color: #efefef;    text-align: center;    font-size: 18px;    font-weight: normal;  }        li {    display: inline-block;    *display: inline;    padding: 8px;    color: #e22f8f;    }    a {      color: #a0616d;      text-decoration: none;      padding: 13px;  }            /*=========================    search bar    ================= */     @import url(https://fonts.googleapis.com/css?family=Open+Sans);     body{     background: #f2f2f1;     font-family: 'Open Sans', sans-serif;   }     .search {     width: 100%;     position: relative   }     .searchTerm {     float: left;     width: 100%;     border: 3px solid #00B4CC;     padding: 5px;     height: 20px;     border-radius: 5px;     outline: none;     color: #9DBFAF;   }     .searchTerm:focus{     color: #00B4CC;   }     .searchButton {     position: absolute;       right: -50px;     width: 40px;     height: 36px;     border: 1px solid #00B4CC;     background: #00B4CC;     text-align: center;     color: #fff;     border-radius: 5px;     cursor: pointer;     font-size: 20px;   }     /*Resize the wrap to see the search bar change!*/     .wrap{     width: 30%;     position: absolute;     top: 50%;     left: 50%;     transform: translate(-50%, -50%);   }  

Solr Sunspot - How to boost belongs_to association on searchable with Sunspot?

Posted: 20 Apr 2016 07:15 AM PDT

I'm using Sunspot Solr for indexing and searching in our Ruby on Rails application with MongoDB database (Mongo mapper)

I have class Article which belongs_to User . I index my object User with Sunspot SOLR. It looks like this:

    class Article      include ActiveModel::Serializers::JSON      include MongoMapper::Document      include Sunspot::Mongo      ...          key :title, String      key :introduction, String      key :cover, String      ...        belongs_to :user      ...        searchable do        text :title, :boost => 5        text :user do          user.username if user        end        string(:category)        boolean(:published)      end  

I am able to search on the user.username field of the Top model successfully but the when I boost this field for exemple like :

  text :user, :boost => 10  do      user.username if user    end  

It's not working, Sunspot ignore the boost totally (the title field works well)

Is it a syntax error ?

Please help !

Thanks.

Why does this happen when i try to update rails to 4.0.0?

Posted: 20 Apr 2016 07:18 AM PDT

I pulled someone's project from github, and we seem to be using different rails versions. When i update the rails gem, it seems to go fine, but when i check the version it still shows the previous one and won't run the rails server.

me@ubuntu:~/Documents/RailsProjects/vega$ gem install rails     --version=4.0.0  Successfully installed rails-4.0.0  Parsing documentation for rails-4.0.0  Done installing documentation for rails after 0 seconds  1 gem installed  me@ubuntu:~/Documents/RailsProjects/vega$ rails -v  Rails 3.2.6  

Is it possible to skip prepend_before_action in Rails 4 and Devise?

Posted: 20 Apr 2016 07:05 AM PDT

I want to enforce authentication to Devise registration controller's new and create function because I am implementing a custom sign_up mechanism that requires an admin to sign in first.

But Devise is forcing require_no_authentication on new and create with prepend_before_action.

According to Rails, I can skip_before_action, however,

how do I force skipping prepend_before_action?

How to define params with has_many through?

Posted: 20 Apr 2016 07:04 AM PDT

I'm using has_many through relationship and I don't really get what should I do else to make it work. I suppose there is something about parameters that I don't understand and omit. If so, please tell me where and how to write it, because I'm confused a little bit because of all these params. book.rb:

class Book < ActiveRecord::Base    has_many :user_books    has_many :users, through: :user_books  end  

user.rb:

class User < ActiveRecord::Base    devise :database_authenticatable, :registerable, :confirmable,      :recoverable, :rememberable, :trackable, :validatable      validates :full_name, presence: true      has_many :user_books    has_many :books, through: :user_books #books_users - book_id user_id    end  

and books_controller.rb:

class BooksController < ApplicationController    before_action :is_admin?, except: [:show_my_books, :book_params]    before_filter :authenticate_user!    expose(:book, attributes: :book_params)    expose(:user_book)    expose(:user_books)    expose(:books){current_user.books}      def create      if book.save        redirect_to(book)      else        render :new      end    end      def update      if book.save        redirect_to(book)      else        render :edit      end    end      def show    end      def is_admin?      if current_user.admin?        true      else        render :text => 'Who are you to doing this? :)'      end    end      def book_params      params.require(:book).permit(:name, :author, :anotation, user:[:name])    end  end  

When I create new book it gives me an error

Couldn't find Book with 'id'=27 [WHERE "user_books"."user_id" = ?]

<%=book.name%>

Sorry for a silly question, but I couldn't find a proper example to understand it myself that's why I ask you for help. Every help would be appreciated, thank you!

Unknown validator: 'ForbidChangingValidator'

Posted: 20 Apr 2016 07:04 AM PDT

I spend few hours trying to find solution of my problem, but lost any hope to understood what i am done wrong.

Rails 4.2.6

my model:

app/models/component.rb

class Component < ActiveRecord::Base      validates :name, presence: true,                   uniqueness: true,              forbid_changing: true #TODO [VS] Fix custom validator autoload      validates :label, presence: true,                    uniqueness: true  end  

my validator:

class ForbidChangingValidator < ActiveModel::EachValidator    def validate_each(record, attribute, value)      if record.send "#{attribute}_changed?".to_sym        record.errors[attribute] << options[:message] || t(:changing_forbidden)      end    end  end  

when try reload the page i got error: Unknown validator: 'ForbidChangingValidator'

ArgumentError - Unknown validator: 'ForbidChangingValidator':    activemodel (4.2.6) lib/active_model/validations/validates.rb:120:in `rescue in block in validates'    activemodel (4.2.6) lib/active_model/validations/validates.rb:117:in `block in validates'    activemodel (4.2.6) lib/active_model/validations/validates.rb:113:in `validates'    app/models/component.rb:6:in `<class:Component>'    app/models/component.rb:1:in `<top (required)>'    activesupport (4.2.6) lib/active_support/dependencies.rb:457:in `block in load_file'    activesupport (4.2.6) lib/active_support/dependencies.rb:647:in `new_constants_in'    activesupport (4.2.6) lib/active_support/dependencies.rb:456:in `load_file'    activesupport (4.2.6) lib/active_support/dependencies.rb:354:in `require_or_load'    activesupport (4.2.6) lib/active_support/dependencies.rb:494:in `load_missing_constant'    activesupport (4.2.6) lib/active_support/dependencies.rb:184:in `const_missing'    activesupport (4.2.6) lib/active_support/inflector/methods.rb:261:in `block in constantize'    activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `constantize'    activesupport (4.2.6) lib/active_support/core_ext/string/inflections.rb:66:in `constantize'    repositor (0.6.0) lib/repositor/active_record.rb:6:in `initialize'  

but when i am trying to call this validator from console i got: !! #<ArgumentError: A copy of Component has been removed from the module tree but is still active!>

I found a lot of messages about thig issue, but can't to resolve mine.

Please, help somebody....

How come methods under 'private' and 'protected' can always be called in models (rails)?

Posted: 20 Apr 2016 07:17 AM PDT

I tested, that they, in fact, don't work:

class User < ActiveRecord::Base      def self.call_protected_method      protected_method    end      def self.call_private_method      private_method    end      protected      def self.protected_method      puts "protected_method"    end      private      def self.private_method      puts "private_method"    end    end  

What i mean, by they don't work, is You can call all methods in this example. It doesn't matter if they are under private and/or protected.

# in rails console:  User.call_protected_method # => protected_method  User.protected_method      # => protected_method  User.call_private_method   # => private_method  User.private_method        # => private_method  

Why is that? Whats the reason for ignoring 'private' and 'protected'?

UPDATE: my question isn't how to do this. My question is why doesn't this approach work in rails models!?

What to code in for a personal intranet

Posted: 20 Apr 2016 06:51 AM PDT

So I've got a home server, its currently running a LAMP server for the intranet, I haven't really started coding anything for it,

I have coded a few site using LAMP so I know how it works, also I code at work in .NET so I don't want to code on that when I get home. Generally I can pick up most languages pretty easy.

The intranet, I am going to use it for planning tools, general organizations things, and anything else I want to mess about with.

I was thinking maybe trying a MEAN stack, just wondered if anyone knew of any other interesting combinations of things that might be worth looking into?

I happy to use it any combinations of things, I was looking into RoR a while a go for the intranet, but there so much to look at, I just wondered what you guys liked to use?

Any Recommendations would be great!

ActiveMerchant IATS ACH response error

Posted: 20 Apr 2016 06:35 AM PDT

When I try to store a token through the IATS Gateway for ACH, it gives me an "undefined method 'start_with?' for nil:NilClass" error. Looking at the response, it has a status of 'Failure' and error of "Object reference not set to an instance of an object." Any idea what's happening? My code is below.

# Active Merchant 1.58.0, Ruby 2.2.2, ActiveSupport 4.2.1, Nokigiri 1.6.7.2    check = ActiveMerchant::Billing::Check.new(    :first_name         => 'Test',    :last_name          => 'Person',    :routing_number     => '111111111',    :account_number     => '12345678',    :account_type       => "checking")    iats_gateway_users = ActiveMerchant::Billing::IatsPaymentsGateway.new(    :login => 'TEST88',    :password => 'TEST88')    iats_gateway_users.store(check, options={ :billing_address => { :address => "1234 Any Street", :city => "Fort Collins", :state => 'CO', :zip_code => '80524' }})  

Kubernetes - ReplicationController and Persistent Disks

Posted: 20 Apr 2016 07:18 AM PDT

I have run into a Kubernetes related issue. I just moved from a Pod configuration to a ReplicationController for a Ruby on Rails app and I'm using persistent disks for the Rails pod. When I try apply the ReplicationController it gives the following error:

The ReplicationController "cartelhouse-ror" is invalid. spec.template.spec.volumes[0].gcePersistentDisk.readOnly: Invalid value: false: must be true for replicated pods > 1; GCE PD can only be mounted on multiple machines if it is read-only

Does this mean there is no way to use persistent disks (R/W) when using ReplicationControllers or is there another way?

If not, how can I scale and/or apply rolling updates to the Pod configuration?

Pod configuration:

apiVersion: v1  kind: Pod  metadata:    name: appname    labels:      name: appname  spec:    containers:          - image: gcr.io/proj/appname:tag        name: appname        env:              - name: POSTGRES_PASSWORD                # Change this - must match postgres.yaml password.            value: pazzzzwd              - name: POSTGRES_USER            value: rails        ports:              - containerPort: 80            name: appname        volumeMounts:                # Name must match the volume name below.              - name: appname-disk-per-sto                # Mount path within the container.            mountPath: /var/www/html    volumes:          - name: appname-disk-per-sto        gcePersistentDisk:              # This GCE persistent disk must already exist.          pdName: appname-disk-per-sto          fsType: ext4  

ReplicationController configuration:

apiVersion: v1  kind: ReplicationController  metadata:        labels:          name: appname        name: appname  spec:        replicas: 2        selector:          name: appname        template:          metadata:            labels:              name: appname          spec:            containers:              - image: gcr.io/proj/app:tag                name: appname                env:                  - name: POSTGRES_PASSWORD                    # Change this - must match postgres.yaml password.                    value: pazzzzwd                  - name: POSTGRES_USER                    value: rails                ports:                  - containerPort: 80                    name: appname                volumeMounts:                    # Name must match the volume name below.                  - name: appname-disk-per-sto                    # Mount path within the container.                    mountPath: /var/www/html            volumes:              - name: appname-disk-per-sto                gcePersistentDisk:                  # This GCE persistent disk must already exist.                  pdName: appname-disk-per-sto                  fsType: ext4  

Not updating attribute in my rails app

Posted: 20 Apr 2016 07:11 AM PDT

I have creating a web application using Ruby on Rails but now I'm troubling a issue which is post updating, I'm trying to solve this issue which followed this also this. Below is my code:

 def update    @edit = Post.find(params[:post_id])    params.permit!    if @edit.update_attributes(params[:post])        redirect_to home_path        flash[:notice] = "Your post updated"    else       flash[:notice] = "Wrong"    end  end  

When I use this code then showing

When assigning attributes, you must pass a hash as an argument.

After that

def update    @edit = Post.find(params[:post_id])    params.permit!    if @edit.update_attributes(update_params)        redirect_to home_path        flash[:notice] = "Your post updated"    else       flash[:notice] = "Wrong"    end  end    private  def update_params   params.require(:post).permit(:title, :details, :summery)  end  

When I use this then showing

param is missing or the value is empty: post

Where is my actual fault?

How to chain "OR" dynamically with Squeel

Posted: 20 Apr 2016 06:36 AM PDT

I want to generate LIKE match with OR combination, which is specified by given queries dynamically.

I can realize that in native ruby like this:

scope :name_search, -> search {    # search = { keywords: "foo bar, any" }    if search[:keywords].present?      keywords = []      search[:keywords].to_s.split(/[\s,]/).map do |k|        keywords.push("name LIKE '%#{k}%'") if k.present?      end      return where(keywords.join(" OR "))    end  }  

and the result is SELECT "users".* FROM "users" WHERE (name LIKE '%foo%' OR name LIKE '%bar%' OR name LIKE '%any%'). Good, this is what I want.

But, how to realize the same thing with using squeel?

I (want to) believe there is already an easier way to do the same thing.

Or, if using arel is easier than squeel to realize this, I would use arel.

Thank you.

can't convert nil into String - gem update --system 1.8.25

Posted: 20 Apr 2016 07:04 AM PDT

While fixing an error , I got an answer from this stack overflow post , which needs me to use

gem update --system 1.8.25 to fix the issue.

But on running gem update --system 1.8.25 , I'm getting following error.

updating rubygems-update ERROR: While executing gem ... (TypeError) can't convert nil into String

How can this be fixed ?

This used to work previously , Suddenly started to give this problem.

Here is my gemfile

# source :gemcutter  source 'http://rubygems.org'    gem "rake", "0.8.7"  gem "rack", "~> 1.1.6"  gem "rails","2.3.18"    gem "json", "~> 1.8"  gem "json-compare", "0.1.8"    gem "mysql2", "0.2.23" #:git => 'git://github.com/sumakumardey/mysql2.git',:branch => 'mysql_logs'    gem "rate-limiting", :git =>"git://github.com/repo-name/rate-limiting.git",:branch => 'itil_rate_limiting'  gem "white_list", :git =>"git://github.com/neubloc/white_list.git"  gem "will_paginate", "~> 2.3.16"  gem "country_select", :git => "git://github.com/stefanpenner/country_select", :tag => 'v1.1.2'  gem "activemerchant", :git => "git://github.com/Shopify/active_merchant", :tag => 'v1.7.0'  gem "acts_as_list", "0.1.4"  gem 'rack-ssl', :require => 'rack/ssl', :git => 'git://github.com/sumakumardey/rack-ssl',:branch => 'ssl'  gem "statsd-ruby", :git => 'git://github.com/sumakumardey/statsd-ruby', :branch =>'custom_stats', :require => 'statsd'    group :development do    gem 'rails-dev-boost', :git => 'git://github.com/thedarkone/rails-dev-boost.git', :branch => "rails-2-3"  end    gem "mail"  gem "i18n", "0.4.2"  gem "RedCloth", "4.2.9"  gem "authlogic", "2.1.6"  gem "httparty", "0.10.0"  gem "omniauth", "1.0"  gem "omniauth-oauth"  gem "tzinfo", "~> 0.3.29"    gem 'debugger', "~> 1.6.8"    gem 'test-unit', '1.2.3'    gem "omniauth-oauth2", "1.0"  gem "omniauth-openid"  gem "omniauth-google"  gem "omniauth-google-oauth2"  gem "omniauth-facebook"  gem "yam"  gem "omniauth-salesforce", :git => "git://github.com/sathishrepo-name/omniauth-salesforce.git", :branch => "master"  gem "omniauth-mailchimp", "~> 1.0.3"  gem "omniauth-constantcontact2", "~> 1.0.4"  gem "nori", "1.1.4"  gem "google-api-client", "~> 0.7.0"  gem "ipaddress", "0.8.0"  gem 'omniauth-shopify-oauth2', "1.0.0"    gem "sidekiq", :git => "git://github.com/PratheepV/sidekiq.git", :branch => "master"    gem "soap4r-ruby1.9", "~> 2.0.5"  gem "jira4r", "0.3.0"  gem "ruby-openid", :git => "git://github.com/repo-name/ruby-openid.git", :require => "openid"  gem "ruby-openid-apps-discovery", "1.2.0"  gem "twilio-ruby", :git => "git://github.com/repo-name/twilio-ruby.git", :branch => "master"  gem "carmen", :git => "git://github.com/jim/carmen.git", :tag => "ruby-18"    gem "ruby-saml", "0.8.1"    gem "arel", "2.0.7"    gem "rubyzip", "0.9.4" , :require => "zip/zip"  gem "riak-client", "1.4.2"    gem "http_accept_language", "1.0.1"    gem "riddle", "1.2.2"    gem "jammit", "0.6.5"  gem "uglifier", "~> 2.1.2"  gem "yui-compressor", :git => "git://github.com/repo-name/ruby-yui-compressor.git"    gem "braintree","2.10.0"  gem "lockfile","1.4.3"    gem "newrelic_rpm","3.8.0.218"    gem "faraday" , "0.9"  gem "twitter", "~> 5.5.1"  gem "gnip-rule", "0.4.1"  gem "curb", "~> 0.8.4"  gem "sanitize", "2.0.3"  gem "koala", "1.10.1"  gem "spreadsheet", "0.6.8"    gem "sax-machine", "~> 0.1.0"    gem "insensitive_hash", "0.2.3"    gem "redis","3.1.0"  gem "redis-namespace", "1.5.2"    gem "resque","1.22.0"  gem "resque-status", "0.4.1"  gem 'resque-scheduler', :require => 'resque_scheduler'    gem 'marketo', :git => "git://github.com/repo-name/Marketo.git"  gem 'rforce'    gem 'after_commit', "1.0.11"    gem 'chargebee', "1.5.7"    gem 'encryptor', '1.1.3'  gem 'ice_cube'    gem "dalli"  #gem 'memcache-client', '1.8.5', :git => "git://github.com/mperham/memcache-client.git"  gem "deadlock_retry", :git => "git://github.com/repo-name/deadlock_retry.git"  gem "lhm", :git => "git://github.com/repo-name/large-hadron-migrator.git"  gem "rinku", :git => "git://github.com/repo-name/rinku.git"    gem "namae", '0.8.4'  gem 'ancestry', '1.3'  gem 'rubytree'  gem 'global_phone'  # gem "global_phone_dbgen", "~> 1.0.0"  gem "useragent", "~> 0.4.16"    gem "active_record_shards","2.7.0", :require => 'active_record_shards'  gem "rack-throttle", "~> 0.3.0"  gem "omniauth-box2", '~> 0.0.1'  gem "static_model", "~> 1.0.4"    gem 'clockwork', '0.4.1'  gem 'wkhtmltopdf-binary', :git => "git://github.com/repo-name/wkhtmltopdf_binary_gem.git"  gem "wicked_pdf", "~> 0.9.10"  gem "pg"  gem "routing-filter", "~> 0.3.1"    gem "cloudfront_asset_host", :git => "git://github.com/repo-name/cloudfront_asset_host.git"    # Please do not update Paperclip unless you can get it Monkey Patched for Imagemagick DoS Bug.  # Please see https://hackerone.com/reports/390   gem "paperclip", "~> 2.8.0"    gem "aws-sdk", "~> 1.11.3"  gem "aws-sdk-resources", "~> 2.0.33"  gem "xml-simple", "~> 1.1.2"    gem "erubis", "2.7.0"  gem "rails_xss", "0.4.0"      gem "ey_config"  gem "therubyracer"  gem "premailer", "~> 1.8.0"    gem "bunny", "1.2.1"    gem "akismetor", :git => "git://github.com/repo-name/akismetor.git"    gem "redis-queue", "0.0.4"    gem "add_pod_support", :path => "#{File.expand_path(__FILE__)}/../vendor/gems/add_pod_support-0.0.1"  gem "custom_fields", :path => "#{File.expand_path(__FILE__)}/../vendor/gems/custom_fields-0.1"    gem "jwt", "1.0.0" #could not use latest gem version(1.2.0) since twilio-ruby gem is using 1.0.0    group :production,:test,:staging do    gem 'tire', :git => "git://github.com/repo-name/tire.git", :branch => "multi_match"    gem 'unicorn', "4.7.0"  end    gem "repo-name_authority", :path => "#{File.expand_path(__FILE__)}/../vendor/gems/repo-name_authority-0.1"  gem "active_presenter", "1.4.0"    group :development,:test do    gem "forgery","0.5.0"    gem "factory_girl", "1.2.3"    gem "mongrel",  '>= 1.2.0.pre2'  end    group :test do    gem "rspec", "1.3.1"    gem "rspec-rails", "1.3.3"    gem "spork", "~> 0.8.0"    gem "mocha", "~> 0.12.8"    gem 'rack-test', '~> 0.6.2'    gem "rr", "1.1.1"    gem "ZenTest", "4.4.1"    gem "autotest-fsevent", "0.1.1"    gem "autotest-growl", "0.2.0"    gem "autotest-rails", "4.1.0"    gem "faker", "~> 1.0.1"    gem "simplecov", "~> 0.7.1"    gem "simplecov-csv"    gem "database_cleaner"  end    group :assets do    gem "sass",          "3.2.19"    gem "compass-rails", "1.0.3"      # Portal grid system is done using susy grids    gem "susy",          "1.0.9"      # To optimize sprite generation    gem "oily_png",     "1.1.1"      # Building custom font icons inside the application    gem "fontcustom",   "1.3.3"  end  

How to limit an association list based on a related model

Posted: 20 Apr 2016 07:03 AM PDT

I know that I should know this, but I cannot seem to figure it out at all and I'm still new to development...

So I have four models...

Appointments

class Appointment < ActiveRecord::Base      belongs_to :user      belongs_to :profile      belongs_to :location  end  

Profiles

class Profile < ActiveRecord::Base        belongs_to :user      has_many :appointments        has_many :profile_locations      has_many :locations, through: :profile_locations      accepts_nested_attributes_for :profile_locations, reject_if: :all_blank, allow_destroy: true      accepts_nested_attributes_for :locations, reject_if: :all_blank, allow_destroy: true    end  

profile_locations

class ProfileLocation < ActiveRecord::Base        belongs_to :profile      belongs_to :location      belongs_to :location_type        accepts_nested_attributes_for :location    end  

and locations

class Location < ActiveRecord::Base        has_many :profile_locations      has_many :profiles, through: :profile_locations        has_many :appointments    end  

On the create appointments page, I already have an associated profile on the record. I also have an association field on my simple_form for locations that I want to be able to assign to the appointment based on those tied to the profile..

I was trying something like this, but cannot seem to getting working.

%td= f.association :location, :as => :collection_select, collection: Location.where( location.profile_location.profile_id: @profile.id ), label_method: :address_1, value_method: :id, include_blank: false, :input_html => {:class => "input-small"}, :label => "Select The Location"  

Am I missing something here or is there an easier way to query this? Any guidance on any of this would be helpful.

Heroku SSL issue

Posted: 20 Apr 2016 06:12 AM PDT

I am wondering if this is an issue on our end or Heroku's end. I installed the SSL add-on ($20/month) and got an SSL cert through my universities IT department (changed the name of some details but you get the idea). I followed the steps listed here: https://devcenter.heroku.com/articles/ssl-endpoint

I am getting an error in chrome that says "Your connection is not private" NET::ERR_CERT_COMMON_NAME_INVALID. Then it also says This server could not prove that it is mydomain.edu; its security certificate is from *.herokuapp.com. This may be caused by a misconfiguration or an attacker intercepting your connection.

I've checked my CSR and it has the mydomain.edu as the CN, I've checked the email that came from my schools IT and the email says mydomain.edu.

When I check the heroku certs command I get the following:

$ heroku certs  Endpoint                   Common Name(s)              Expires               Trusted  -------------------------  --------------------------  --------------------  -------  tokyo-13550.herokussl.com  mydomain.edu                2019-04-14 23:59 UTC  True  

The only issue I can see wrong is the CNAME record. I believe the endpoint changed when I added SSL:

$ heroku certs:add cert.cer private.key --app myapp  Resolving trust chain... done  Adding SSL Endpoint to myapp... done  myapp now served by tokyo-13550.herokussl.com  Certificate details:  Common Name(s): mydomain.edu  Expires At:     2019-04-14 23:59 UTC  Issuer:         /C=US/ST=MI/L=Ann Arbor/O=Internet2/OU=InCommon/CN=InCommon RSA Server CA  Starts At:      2016-04-14 00:00 UTC  Subject:        /C=US/postalCode=myzip/ST=mystate/L=mycity/street=myaddress/O=myorginization/OU=Certificate Management/CN=mydomain.edu  SSL certificate is verified by a root authority.  

I initially was running the app without SSL and we setup a CNAME record with this endpoint:

us-east-1-a.route.herokuapp.com   

I believe that if we update the CNAME record from the US to the Tokyo one then the SSL issue will be solved, my IT department believes I installed the cert wrong or it is using the old cert since it says *.herokuapp.com instead of referencing mydomain.edu.

Doorkeeper new_oauth_application_path not found

Posted: 20 Apr 2016 06:11 AM PDT

I test the new rails 5 api. I want to create a oauth2 server consumme by a js client.

I use Doorkeeper to manage the oauth2 server.

In my routes.rb i have

Rails.application.routes.draw do      use_doorkeeper  end  

doorkeeper.rb

resource_owner_authenticator do    User.find_by_id(session[:user_id]) || redirect_to(new_user_session_url)  end  

When i go to 'http://localhost:3000/oauth/applications', i got the error:

ActionView::Template::Error (undefined local variable or method `new_oauth_application_path' for #<#<Class:0x007fbf1f70c908>:0x007fbf1f72f8b8>)  

Is doorkeeper not fully functionnal with rails 5 ? If it's not, do you known some gem like Doorkeeper ?

browserify-rails error messages don't mention the original source file?

Posted: 20 Apr 2016 06:11 AM PDT

Am loving browserify-rails with babel es6 support! But I am troubled by errors like this one because there's no mention of the original source file location so very difficult for me to debug/fix. Clearly this (below) is just a botched require/import/export in a .js file, but without reference to the source path, it takes a lot of sleuthing to fix... What am I missing?

Started GET "/" for 127.0.0.1 at 2016-04-20 06:00:00 -0700    ActiveRecord::SchemaMigration Load (0.4ms)  SELECT "schema_migrations".* FROM "schema_migrations"  Processing by ClientController#load as HTML    Rendered client/load.html.erb within layouts/client (1.6ms)  Browserify: /Users/eric/Dropbox/calcium/node_modules/.bin/browserifyinc -d --transform babelify --list --cachefile=/Users/eric/Dropbox/calcium/tmp/cache/browserify-rails/browserifyinc-cache.json -o "/Users/eric/Dropbox/calcium/tmp/cache/browserify-rails/output20160420-21848-1xfzor9" -  Completed 500 Internal Server Error in 361ms (ActiveRecord: 0.0ms)    ActionView::Template::Error (Error while running `/Users/eric/Dropbox/calcium/node_modules/.bin/browserifyinc -d --transform babelify --list --cachefile=/Users/eric/Dropbox/calcium/tmp/cache/browserify-rails/browserifyinc-cache.json -o "/Users/eric/Dropbox/calcium/tmp/cache/browserify-rails/output20160420-21848-1xfzor9" -`:    module.js:328      throw err;      ^    Error: Cannot find module '../'      at Function.Module._resolveFilename (module.js:326:15)      at Function.Module._load (module.js:277:25)      at Module.require (module.js:354:17)      at require (internal/module.js:12:17)      at Object.<anonymous> (/Users/eric/Dropbox/calcium/node_modules/.bin/browserifyinc:3:29)      at Module._compile (module.js:410:26)      at Object.Module._extensions..js (module.js:417:10)      at Module.load (module.js:344:32)      at Function.Module._load (module.js:301:12)      at Function.Module.runMain (module.js:442:10)  ):  

Rails server error with strange symbols in requests.accepts: "[\"\\xE2\\x80\\x8B/\\xE2\\x80\\x8B\"]"

Posted: 20 Apr 2016 07:02 AM PDT

I routinely like to clean up 500 errors that come through Airbrake. I'm running a Rails 4.2.4 site in production and I get a recurring error which I'm finding quite puzzling.

The error is:

Missing partial shared/_rhs with {:locale=>[:en], :formats=>["\xE2\x80\x8B/\xE2\x80\x8B"], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml, :jbuilder]}.

Looking at the env section of Airbrake for the error, the related section appears to be:

"action_dispatch.request.accepts": "[\"\\xE2\\x80\\x8B/\\xE2\\x80\\x8B\"]", "action_dispatch.request.content_type": "", "action_dispatch.request.flash_hash": "", "action_dispatch.request.formats": "[\"\\xE2\\x80\\x8B/\\xE2\\x80\\x8B\"]",

It looks like the browser (self-identifying as Chrome) is asking for an unrecognised format, but I have no idea why it would be doing so. It also seems to be asking for just the head.

I can just ignore it, but if anyone has any ideas as to why it occurs in the first place, I would be interested.

The full env (with identifying content items removed) is:

{ "DOCUMENT_ROOT": "[******]", "HTTPS": "on", "HTTP_ACCEPT": "​/​", "HTTP_ACCEPT_ENCODING": "gzip,deflate,sdch", "HTTP_ACCEPT_LANGUAGE": "en-US,en;q=0.8", "HTTP_CACHE_CONTROL": "no-cache", "HTTP_CONNECTION": "keep-alive", "HTTP_HOST": "[******]", "HTTP_PRAGMA": "no-cache", "HTTP_USER_AGENT": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.49 Safari/537.36", "ORIGINAL_FULLPATH": "[******]", "ORIGINAL_SCRIPT_NAME": "", "PASSENGER_APP_ENV": "live", "PASSENGER_APP_TYPE": "rack", "PASSENGER_SHOW_VERSION_IN_HEADER": "false", "PATH_INFO": "[******]", "QUERY_STRING": "", "REMOTE_ADDR": "[******]", "REMOTE_PORT": "47888", "REQUEST_METHOD": "HEAD", "REQUEST_URI": "[******]", "ROUTES_40753200_SCRIPT_NAME": "", "ROUTES_48254480_SCRIPT_NAME": "", "SCGI": "1", "SCRIPT_NAME": "", "SERVER_ADDR": "[******]", "SERVER_NAME": "[******]", "SERVER_PORT": "443", "SERVER_PROTOCOL": "HTTP/1.1", "SERVER_SOFTWARE": "nginx/1.6.0", "action_dispatch.cookies_digest": "", "action_dispatch.cookies_serializer": "", "action_dispatch.parameter_filter": "[\"password\"]", "action_dispatch.redirect_filter": "[]", "action_dispatch.remote_ip": "[******]", "action_dispatch.request.accepts": "[\"\\xE2\\x80\\x8B/\\xE2\\x80\\x8B\"]", "action_dispatch.request.content_type": "", "action_dispatch.request.flash_hash": "", "action_dispatch.request.formats": "[\"\\xE2\\x80\\x8B/\\xE2\\x80\\x8B\"]", "action_dispatch.request.parameters": { "action": "show_by_tag_and_slug", "controller": "[******]", "slug": "[******]", "tag": "[******]" }, "action_dispatch.request.path_parameters": { "action": "show_by_tag_and_slug", "controller": "[******]", "slug": "[******]", "tag": "[******]" }, "action_dispatch.request.query_parameters": "", "action_dispatch.request.request_parameters": "", "action_dispatch.request_id": "f120141c-58e6-4429-ad98-1ab352f1c7ce", "action_dispatch.show_detailed_exceptions": "false", "action_dispatch.show_exceptions": "true", "newrelic.transaction_started": "true", "preview_manager": "#<Preview::Manager:0x007fa334e8eca0>", "rack.hijack": "#<Proc:0x007fa34ee79020@/home/release/.rvm/gems/ruby-2.2.2/gems/passenger-4.0.53/lib/phusion_passenger/rack/thread_handler_extension.rb:69 (lambda)>", "rack.hijack?": "true", "rack.multiprocess": "true", "rack.multithread": "false", "rack.request.query_hash": "", "rack.request.query_string": "", "rack.run_once": "false", "rack.url_scheme": "https", "rack.version": "[\"1\", \"2\"]", "warden": "Warden::Proxy:70169690063580 @config={:default_scope=>:user, :scope_defaults=>{}, :default_strategies=>{:user=>[:rememberable, :database_authenticatable]}, :intercept_401=>false, :failure_app=>#<Devise::Delegator:0x00000004e859a0>}" }

Rails 4.2: Set domain for ALL cookies

Posted: 20 Apr 2016 06:30 AM PDT

I need to ensure that ALL COOKIES set by my application (session, normal cookies, whatever) uses the top level domain (ie. ".mydomain.com").

I can see how to do this when setting an individual cookie, but I need to ensure it's set for every cookie.

I'm goin' crazy here. Help a guy out!

flash message type :success appears as :error

Posted: 20 Apr 2016 06:16 AM PDT

from controller I 'm sending flash message as

redirect_to admin_root_path,:flash => { :success => "Password Changed successfully" }  

but when I try to check its type in layout using

<% flash.each do |type, msg| %>      <%= content_tag :div, type,class: "alert alert-danger" %>  <% end %>  

It display its type as "error" while I passed type as "success"

whats going wrong with this?

Why does ActionCable could not transmit from a channel for some computers in production?

Posted: 20 Apr 2016 05:55 AM PDT

I've recently deployed ActionCable to my stage server. I've stuck with a kind of a weird problem. For some computers it works as expected. However, for another it establishes connection with a server, but could not transmit information from the channel. So that it constantly sends requests to /cable.

When I do curl -i -N -H "Connection:Upgrade" -H "Upgrade:websocket" -H "Host:example.com" -H "Origin:http://example.com" form my computer, I have a response curl: (52) Empty reply from server. But from another one, the connection is established and I can receive data.

I use nginx with the following config:

upstream unicorn {    server unix:/tmp/unicorn.my_app.sock fail_timeout=0;  }    upstream puma {     server unix:/var/www/my_app/shared/tmp/sockets/puma.sock   fail_timeout=0;  }    server {    listen 80;    server_name staging.my_app.com;        root /var/www/my_app/current/public;      location ^~ /assets/ {      gzip_static on;      expires max;      add_header Cache-Control public;    }      try_files $uri/index.html $uri @unicorn;    location @unicorn {      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header Host $http_host;      proxy_redirect off;      proxy_pass http://unicorn;    }      location /cable {      proxy_pass http://puma;      proxy_http_version 1.1;      proxy_set_header Upgrade $http_upgrade;      proxy_set_header Connection "Upgrade";    }      error_page 500 502 503 504 /500.html;    client_max_body_size 4G;    keepalive_timeout 10;  }  

Any kind of help would be great!

Capybara cannot find a link on a modal which changes on button press

Posted: 20 Apr 2016 05:52 AM PDT

I have a rails project using rspec 3.4.0 capybara 2.6.2 and capybara-webkit 1.8.0.

I am writing a feature test for a flow on my site which looks like the following:

scenario "Buyer creates a seller profile", :js => true do     click_link("SELL ON MYSITE",match: :first)     expect(page).to have_text("Reach thousands of customers in your area")     click_link("Create an Activity",match: :first)     expect(current_path).to eql (new_seller_profile_path)        fill_in "seller_profile[business_name]", :with => "Test company"      fill_in "seller_profile[business_email]", :with => "test@email.com"      fill_in "seller_profile[business_phone_number]", :with => "07771330510"      fill_in "seller_profile[business_description]", :with => "This is a test company"        find('label[for="social"]').click          find("#facebook-placeholder").click        fill_in "seller_profile[business_facebook_url]", :with => "https://www.facebook.com/test"        click_button("CREATE AN ACTIVITY")  

------this button opens a modal after the page changes --------

    fill_in "seller_profile[requested_postcode]", :with => "EH21 8PB"        click_button("Submit")        save_and_open_screenshot  

------this is where it goes wrong-------

    click_link("Continue")        expect(page).to have_text("Choose the type of activity that you want to create")     end  

The click_link continue fails with error:

Failure/Error: click_link("Continue")         Capybara::ElementNotFound:         Unable to find link "Continue"  

The link actually does exist - when you click on the submit button some javascript executes which changes the contents of the modal to display some new text and a new button. However for some reason click_link does not wait or look in the modal, it fails straight away.

Having added a save_and_open_screenshot call we can see this situation as the modal javascript has yet to execute as we can still see the submit button :

enter image description here

How can I make the click_link wait until the continue button appears?!

This is the javascript which executes on press of 'submit' added to the modal which changes it:

$('#gate .modal-body .intro').text('Congratulations, we are available in your location, please continue to create your activity.');    $('#gate .modal-footer').append('<a class="btn btn-lg btn-primary" href="/events/new/">Continue</a>');  

Production log in RoR heroku app

Posted: 20 Apr 2016 05:59 AM PDT

I have a bunch of logging statements when important database changes are made. For example,

def update    @user = User.find(params[:id])    if @user.update_attributes(user_params)      logger.info "INFO -- #{Time.now} -- User #{@user.first_name} #{@user.last_name} (ID: #{@user.id}) updated their profile"      flash[:success] = "Profile updated"      redirect_to @user    else      render 'edit'    end  end  

I can get these by searching through the output of heroku logs, but it seems that heroku only keeps about 1000 lines of logging so my statements get pushed out. Is there a way to save these to a file and keep only the "INFO" statements up to a certain number of lines (something like 10000)?

Alternatively, would it be possible to "turn off" output like

2016-04-20T10:28:52.031573+00:00 app[web.1]:   Role Load (0.8ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'scout') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 135]]  2016-04-20T10:28:52.046090+00:00 app[web.1]:   Role Load (0.8ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'scout') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 143]]  2016-04-20T10:28:52.056567+00:00 app[web.1]:   Rendered layouts/_shim.html.erb (0.1ms)  2016-04-20T10:28:52.060492+00:00 app[web.1]:   Rendered layouts/_footer.html.erb (0.2ms)  2016-04-20T10:28:52.060925+00:00 app[web.1]: Completed 200 OK in 215ms (Views: 167.9ms | ActiveRecord: 41.7ms)  2016-04-20T10:28:52.048956+00:00 app[web.1]:   User Load (0.8ms)  SELECT  "users".* FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."followed_id" WHERE "relationships"."follower_id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["follower_id", 143]]  2016-04-20T10:28:52.057903+00:00 app[web.1]:   CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 165]]  2016-04-20T10:28:52.050240+00:00 app[web.1]:   CACHE (0.0ms)  SELECT  "users".* FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."followed_id" WHERE "relationships"."follower_id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["follower_id", 143]]  2016-04-20T10:28:52.058796+00:00 app[web.1]:   CACHE (0.0ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'der') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 165]]  

?

How to test whether right template is rendered (RSpec Rails)?

Posted: 20 Apr 2016 05:46 AM PDT

Im trying to grasp some concepts of TDD and in my RoR app I have /about view which belongs to static_pages#about. It has route defined in routes.rb get 'about' => 'static_pages#about'. Everything works so far in browser but I want to test it by RSpec as well. Given

RSpec.describe "about.html.erb", type: :view do    it "renders about view" do      render :template => "about"      expect(response).to render_template('/about')    end  end  

raises an error

Missing template /about with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :......  

Thanks!

Recive JS object and fetch data from database

Posted: 20 Apr 2016 06:51 AM PDT

I am using Angular in frontend and I am trying to send object such as:

obj = {    "foo" : "1",    "bar" : 2,    "baz" : 3  }  

And when Rails recives this object, it should send back data from database depending on these parameters. This is my current method to create API:

  def index      @tickets = Ticket.select(        'id',        'departure_date',        'departure_country',        'departure_country_tag'      )      render status:200, json: { tickets: @tickets}    end  

However this fetches all data from database. I only want to fetch data that matches parameters from the object.

Any suggestion on how to do this properly?

How to create the model relation between a post and its image attachment considering that the image is uploaded before the post is created?

Posted: 20 Apr 2016 05:35 AM PDT

I have a post model. To create a new post, on the form that does so, on the content field, I'm using a Richtext editor which has the capability of inserting images by uploading them first. So the images are uploaded before the actual post is created.

This seems to be a classic belongs_to - has_many relation between images and posts. But I'm not sure how to create this relation and if such a relation is the way to go altogether ? The only thing that comes to mind is to create an after_action in the controller after create which scans the post content and updates each image with the post_id.

But also some images may actually not belong to any post, because after being uploaded the user may decide to not create the post.

What would be the best way to go about this ?

Searchkick only return certain values, not all

Posted: 20 Apr 2016 06:24 AM PDT

When using searchkick to perform a search I get all fields as a result. I would like to limit the response to only output certain fields like title.

# movie.rb  class Movie < ApplicationRecord    searchkick autocomplete: ['title']  end    # search_controller.rb  def autocomplete    render json: Movie.search(params[:query], autocomplete: true, limit: 10, fields: [:title])  end  

My response is still

[{"id":1,"title":"Megamind","director":"Tom McGrath","genre":"Animation | Action | Comedy","description":"The supervillain Megamind finally defeats his nemesis, the superhero Metro Man. But without a hero, he loses all purpose and must find new meaning to his life.","length":95,"year":2010,"imdb_id":"tt1001526","imdb_rating":"7.3","created_at":"2016-04-16T19:50:24.893Z","updated_at":"2016-04-16T19:50:24.893Z"}]  

I am trying to only get the title back. Reading through different questions I assumed it should have to do with fields in my search, but that doesn't change the response. I also tried using the _source-attribute, but no luck.

Unable to establish a secure connection to Stripe using Rails

Posted: 20 Apr 2016 05:21 AM PDT

I'm following an online tutorial to establish stripe payments. After entering the card details in test mode, the instructor's page displayed a message "Payment successful" from create.html.erb file.

However, I'm stuck with an error saying Stripe::APIConnectionError in ChargesController#create Please check the screenshot below, it says it has something to do with Openssl version although I've the latest version installed.

Error message I got

After running the command it asked me to, I got this displayed in my cmd: Verify return code: 20 (unable to get local issuer certificate)

charges_controller.rb

class ChargesController < ApplicationController        def create      # Amount in cents      @amount = 500        customer = Stripe::Customer.create(        :email => params[:stripeEmail],        :source  => params[:stripeToken]      )        charge = Stripe::Charge.create(        :customer    => customer.id,        :amount      => @amount,        :description => 'Rails Stripe customer',        :currency    => 'usd'      )      rescue Stripe::CardError => e      flash[:error] = e.message      redirect_to new_charge_path    end    end  

I recently started learning Rails, any help on this would be appreciated. Thank you!

Save array in DB when checked more than one checkbox

Posted: 20 Apr 2016 05:37 AM PDT

I have a problem greatest!! I guess that really want Array, look my console when I checked just one:

{"value_solve"=>["", "", "333", ""], "contract_number"=>["33"]}  -----    SQL (317.5ms)  UPDATE "authorizations" SET "value_solve" = '', "situation" = 2 WHERE "authorizations"."contract_number" = ?  [["contract_number", "33"]]  

After, when I checked just one, the first:

{"value_solve"=>["111", "", "", ""], "contract_number"=>["11"]}  -----    SQL (317.5ms)  UPDATE "authorizations" SET "value_solve" =  '111 ', "situation" = 2 WHERE "authorizations"."contract_number" = ?  [["contract_number", "11"]]  

And, for last, when I just more then one:

{"contract_number"=>["11", "44"], "value_solve"=>["111", "", "", "444"]}  -----    SQL (297.7ms)  UPDATE "authorizations" SET "value_solve" = '111', "situation" = 2 WHERE "authorizations"."contract_number" = ?  [["contract_number", "11"]]    SQL (121.9ms)  UPDATE "authorizations" SET "value_solve" = '', "situation" = 2 WHERE "authorizations"."contract_number" = ?  [["contract_number", "44"]]  

And this is my controller:

@selected_ids = params[:authorization][:contract_number]    @authorizations = Authorization.where("contract_number in (?)", @selected_ids)    auth_params = params[:authorization]    auth_params[:contract_number].zip(auth_params[:value_solve]).each do |contract_number, value_solve|        Authorization.where(contract_number: contract_number).update_all(value_solve: value_solve, situation: 2)    end  

Just save the first value on DB, how I can save more then one value? Thanks!

1 comment:

  1. awesome post presented by you..your writing style is fabulous and keep update with your blogsRuby on Rails Online Course

    ReplyDelete