Wednesday, August 31, 2016

Heroku: Sendgrid add-on with custom domain | Fixed issues

Heroku: Sendgrid add-on with custom domain | Fixed issues


Heroku: Sendgrid add-on with custom domain

Posted: 31 Aug 2016 08:19 AM PDT

I'm trying to set up the Heroku Sengrid plugin for a custom domain. I need it because we have ssl certificate on the custom domain, not on the basic .herokuapp.com.

The feature: reset your password email from devise.

In my config/environments/production.rb, I have this line:

config.action_mailer.default_url_options = { :host => ENV['MAILER_URL'] }

When the MAILER_URL variable is set to basic_domain.herokuapp.com, I can send an email for resetting a password. But the links in it will lead to the scary page 'this site is not secure, are you sure?'.

I can also set the MAILER_URL variable to great_custom_domain.com, which has an ssl certificate. But the email will never be send, and in my server log I can read :

Net::SMTPAuthenticationError (451 Authentication failed: Could not authenticate).

After reading other answers, I double checked the Sendgrid credentials.

Activeadmin: Filtering in index do

Posted: 31 Aug 2016 08:07 AM PDT

I am learning about activeadmin. I want that a column in my "index do" of my site display only certain values rather all. For example in my site there is a column score. This column shows the following values

11 10 5 6 7

then I need to know what method to use in the next lines

index do     column : score  end do  

to show only the values greater then 8. I am trying

index do     column : score > 8  end do  

but this does not work

Template is missing - Rails

Posted: 31 Aug 2016 08:20 AM PDT

i'm gotting this error from my web page, when i try to go to "localhost:3000/suscribir" i got this error:

Missing template subscribe/create, application/create with {:locale=>[:es, :en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.  

this is my routes.rb file...

  post '/suscribir' => 'subscribe#create'    mount Refinery::Core::Engine, at: Refinery::Core.mounted_path  

this is the subscribe controller...

class SubscribeController < ApplicationController    def create      logger.info "suscripcion #{params.inspect}"      user = user_params(params)      MailchimpWrapper.subscribe(user, params[:group_name], params[:group])      redirect_to '/gracias'    rescue Mailchimp::Error => e      logger.error "ERROR mailchimp #{e.message} #{params.inspect}"    end      private      def user_params(params)      user = {        email: params[:email].try(:downcase),        first_name: params[:first_name].try(:titleize),        last_name: params[:last_name].try(:titleize),        city: params[:city].try(:titleize),        phone: params[:phone],        comment: params[:comment].try(:titleize)      }      user    end  end  

You can check the line "redirect_to '/gracias'"

and this is the gracias.html.erb :

<section class="container thanks-subscribe">    <span>Gracias por suscribirte!</span>    <p>Si es la primera vez que te registras a nuestra lista de contactos, revisa tu correo. Te estaremos enviando un correo de confirmación</p>    <a href="/home"><button>Regresa a la página principal y sigue navegando</button></a>  </section>  

without rescue from mailchimp i got this error..

SyntaxError in SubscribeController#create  C:/Sites/ifurniture/app/controllers/subscribe_controller.rb:22: syntax error, unexpected end-of-input, expecting keyword_end  

i'll be watching for your help, thanks.

rails: add row to fixed header table using ajax

Posted: 31 Aug 2016 07:34 AM PDT

I have a fixed header table that scrolls the rows when they pass the fixed height. I'm adding new rows via ajax. But if I add a new one and the rows are below the max height, the new row won't appear. If its after the max height the table previous table shrinks and the new row appears at the end.

this is my ajax call:

$('.table_meetings').append(" <%= j render partial: 'projects/new_overview_partials/meeting', locals: {dd: @issue} %>");  

and this is my table:

<table class="table_meetings scroll">    <thead class="header">        <tr class="myspan1 title">            <th style="width: 39.5%; padding-left: 10px">Name</th>        </tr>  </thead>        <tbody >          <% @total.each do |dd| %>              <%= render partial: 'projects/new/rows', locals: {dd: dd} %>            <% end %>        </tbody>      </table>  

css:

.table_meetings{      border-collapse:collapse;      width: 100%;      font-size: 11pt;    }      .table_meetings th {      font-size: 11pt;      text-align: left;      padding-top: 10px;      padding-bottom: 10px;    }      .table_meetings tr p{      padding-bottom: 5px;      margin-bottom: 0px;    }    .table_meetings tr a{      font-size: 11pt !important;    }      .table_meetings td{      padding-top: 10px;      padding-bottom: 10px;      border-bottom: 5px solid white;      height: 40px;    }      table.scroll {      width: 100%;       border-spacing: 0;    }      table.scroll tbody { display: block; }    table.scroll thead { display: inherit; }      thead tr th {      height: 30px;      line-height: 30px;    }      table.scroll tbody {      height: 700px;      overflow-y: auto;      overflow-x: hidden;    }  

Combining scopes doesn't work

Posted: 31 Aug 2016 07:33 AM PDT

I'm trying to combine three scopes in one (one scope uses the other two).

I want to get all videos which don't have certain categories and certain tags.

Video

class Video < ActiveRecord::Base      self.primary_key = "id"      has_and_belongs_to_many :categories      has_and_belongs_to_many :tags        scope :with_categories, ->(ids) { joins(:categories).where(categories: {id: ids}) }      scope :excluded_tags, -> { joins(:tags).where(tags: {id: 15}) }        scope :without_categories, ->(ids) { where.not(id: excluded_tags.with_categories(ids) ) }    end  

But when I call

    @excluded_categories = [15,17,26,32,35,36,37]      @videos = Video.without_categories(@excluded_categories)  

I still get video which has tag 15

Am I doing something wrong?

How to disable render on send_data

Posted: 31 Aug 2016 08:15 AM PDT

I am attempting to create an attachment upload and download system in a messaging system for a rails app. The application is using a salesforce database:

def download_attachment      @attachment = some_salesforce_object      file = File.open(@attachment[:Name], 'wb')      send_data file, :filename => @attachment[:Name], :disposition => 'Attachment'  end  

the link is here:

<%= link_to 'download', download_attachment_path(:letter_id => params[:letter_id], :child_id => @child.sf_id)%>   

The code above renders a blank screen with a single character : '#' and does not download the file. If I hit refresh it downloads the file properly while remaining on the plain page with the # character.

The desired behavior is that I simply click to download the attachment and it downloads without rendering anything. I have come to understand that send_data is in and of itself a render, so I imagine that I am going about this totally wrong.

Unable to pass parameters to controller in POST AJAX

Posted: 31 Aug 2016 08:01 AM PDT

I cannot pass parameters to controller action in ajax POST request. There is my code :

 $("#sendSubCatButton").click(function(){      var catId = $("#category_name").data("id");      var subCatName = $("#sous_category_name").val();      var lvlUrgenceMax = $("#sous_category_lvl_urgence_max option:selected").val();      // alert(catId);      // alert(subCatName);      // alert(lvlUrgenceMax);      $.ajax({        url: '/sous_categories',        type: 'POST',        dataType: 'json',        data: {            name: subCatName,            category_id: catId,            lvl_urgence_max: lvlUrgenceMax        }      });    });  

And my controller (only the parts concerned) :

  def create      @create_new_subcategory = verifRight('create_new_subcategory')      if @create_new_subcategory        @category = Category.find(params[:category_id])        @sous_category = SousCategory.new(sous_category_params)        # Any category have a 'lvl_urgence_max', for those who create an incident.        # With that, we can determine how many an incident is important.        @sous_category.lvl_urgence_max.nil? ? @sous_category.lvl_urgence_max = 10 : false        respond_to do |format|          if @sous_category.save            format.json { render json: @sous_category.id, status: :created }            format.html { redirect_to edit_category_path(@category), notice: 'Vous venez de créer une sous catégorie.' }          else            format.json { render json: @sous_category.errors, status: :unprocessable_entity }            format.html { redirect_to :back, notice: 'Impossible de créer la sous catégorie.' }          end        end      else        renderUnauthorized      end    end  

...

  def sous_category_params      params.require(:sous_category).permit(:name, :category_id, :lvl_urgence_max)    end  

In console there are that :

Started POST "/sous_categories" for 127.0.0.1 at 2016-08-31 16:08:56 +0200
Processing by SousCategoriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"EDqyXaq+2PekfJrLrmn/+16AnirzvySD+hkZj5+cQee2JD2ddMudDRJWXlZkCfKJ3mzw2AWuVAeCPr/y0Y1WVw==", "sous_category"=>{"name"=>"efsefesf", "lvl_urgence_max"=>"10"}}

EDIT : I commented the "alerts" but I can see the value of the var "CatId" in the alert popup but it is not passed.

How to configure routes for different user models using devise?

Posted: 31 Aug 2016 07:21 AM PDT

I have two different user groups, User and Flyer.

I have generated views and controllers for both the models using,

rails g devise:controllers users/flyers   

and for views:

rails g devise:views users/flyers  

This is my routes.rb:

Rails.application.routes.draw do      devise_for :flyers    devise_for :admins    resources :currencies    resources :broadcasts      devise_for :users, controllers: {          sessions: 'users/sessions',              registrations: 'flyers/registrations'          }      devise_for :flyers, controllers: {      sessions: 'flyers/sessions',    }  end  

But I am getting error for devise for flyers controllers route:

Invalid route name, already in use: 'new_flyer_session' You may have defined two routes with the same name using the `:as` option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with `resources` as explained here: http://guides.rubyonrails.org/routing.html#restricting-the-routes-created  

How can I have different routes? Thanks

How can I implement ADFS with a Heroku Rails app?

Posted: 31 Aug 2016 07:09 AM PDT

Our company has a Rails application hosted on Heroku. It currently uses Devise for user authentication.

One of our clients wants to know if their users could access our application using their ADFS implementation.

  1. Would we be able to use Heroku Integrated security with Identity Federation?
  2. Would we need a 3rd party like Auth0?
  3. Can Devise use ADFS?
  4. Should we use OmniAuth SAML?

Not sure where to start.

How to disable Rails 5 "X-Request-Id" header

Posted: 31 Aug 2016 06:49 AM PDT

On Rails 5, all requests includes an unique identifier accessible on application and displayed on HTTP response headers, called "X-Request-Id".

This identifier is very useful for debugging and logging, but I'm having trouble with this in a very old web client.

I tried to clear the header but it did not work.

response.headers['X-Request-Id'] = nil  

How can I remove this information from headers?

Google Analytics API with Ruby on Rails

Posted: 31 Aug 2016 06:48 AM PDT

I am trying to add Google analytics API to my Rails Appication using Oauth.

I am using google-api-client gem and using http://readysteadycode.com/howto-access-the-google-analytics-api-with-ruby as a reference.

Am able to create to create Client Object but when I am trying to access data

class GoogleController < ApplicationController      def redirect      client = Signet::OAuth2::Client.new({        client_id: GOOGLE_API_CLIENT_ID,        client_secret: GOOGLE_API_CLIENT_SECRET,        authorization_uri: 'https://accounts.google.com/o/oauth2/auth',        scope: Google::Apis::AnalyticsV3::AUTH_ANALYTICS_READONLY,        redirect_uri: 'http://skreem.dev:3000/auth/google/callback'      })        redirect_to client.authorization_uri.to_s    end      def callback      client = Signet::OAuth2::Client.new({        client_id: GOOGLE_API_CLIENT_ID,        client_secret: GOOGLE_API_CLIENT_SECRET,        token_credential_uri: 'https://accounts.google.com/o/oauth2/token',        redirect_uri: 'http://skreem.dev:3000/auth/google/callback',        code: params[:code]      })        response = client.fetch_access_token!      session[:access_token] = response['access_token']        redirect_to url_for(:action => :analytics)    end      def analytics      client = Signet::OAuth2::Client.new(access_token: session[:access_token])        service = Google::Apis::AnalyticsV3::AnalyticsService.new      service.authorization = client        @account_summaries = service.list_account_summaries    end    end  

and am using correct access token but getting following error

Sending HTTP get https://www.googleapis.com/analytics/v3/management/accountSummaries?  Caught error Missing token endpoint URI.  Error - #<ArgumentError: Missing token endpoint URI.>  

Extract year from string, check if successful

Posted: 31 Aug 2016 07:23 AM PDT

I would like to check whether a year was found within a string. Something like

if string.scan(/\d{4}/).first == TRUE  

for example a string looks like "there were 3 earthquakes in 2007"

Any suggestions?

How can I convert my json response in a string

Posted: 31 Aug 2016 07:08 AM PDT

I have this in my controller:

render json: gerencia.pay_charge(params: params, body: payment)  

It returns something like that:

{"code"=>200, "data"=>{"barcode"=>"03399.75039 21000.000006 74992.301015 6 69020000002250", "link"=>"https://exmaple.com.br/emissao/110276_19_NAEMAL1/A4XB-110276-74992-XILE0"}}   

I need to return a string. How can I convert it to a string? I need return something like that:

"{"code"=>200, "data"=>{"barcode"=>"03399.75039 21000.000006 74992.301015 6 69020000002250", "link"=>"https://exmaple.com.br/emissao/110276_19_NAEMAL1/A4XB-110276-74992-XILE0"}}"  

Facets, aggregations elasticsearch error / method rails

Posted: 31 Aug 2016 06:46 AM PDT

I need to do facets for my app. For the moment, I want facets appear on the result page after search. I new on rails and sorry for my bad english, i m french.

I have 2 models : Camping.rb and Caracteristiquetest.rb. I made association has_many / belongs_to. In caracteristiquetest, I have one column camping_id and other string columns "piscine" and "barbecue".

So, after lot of tests, I found a solution to find a post with value "non" on caracteristiquetest.barbecue (see after). Now i try to implement this on app. but i always have some errors...

Error :

C:/Sites/campsite/app/models/camping.rb:66: syntax error, unexpected ':', expecting => {caracteristiquetest.barbecue : "non"}}] ^ C:/Sites/campsite/app/models/camping.rb:66: syntax error, unexpected '}', expecting keyword_end {caracteristiquetest.barbecue : "non"}}] ^ C:/Sites/campsite/app/models/camping.rb:85: syntax error, unexpected end-of-input, expecting keyword_end

How can do to fix it ? By the way, after fixing that how i can implant this on my wiew ? I want to implant this function after search to allow user to filter "barbecue" "yes" / "no".

Thanks for your help.

_search with head_plugin elasticsearch When i run this i have the good result

{  "query": {    "bool": {      "must": [        {"term":           {"caracteristiquetest.barbecue": "non"}}]    }   }  }  

campings_controller.rb

  def homesearch        @campings = Camping.custom_search((params[:q].present? ? params[:q] : '*'))    end    #Page de résultats    def result      if params[:q].blank?        redirect_to action: :index and return      else      @campings = Camping.custom_search((params[:q].present? ? params[:q] : '*')).page(params[:page]).per(14).results      end        end  

camping.rb

   mapping do     indexes :name, boost: 8     indexes :adresse     indexes :commune, boost: 10     indexes :description     indexes :nomdep, boost: 10     indexes :nomregion, boost: 10     indexes :ville_id     indexes :region_id     indexes :departement_id     indexes :latitude     indexes :longitude     indexes :etoile     indexes :user_id     indexes :caracteristiquetest_id     #On implante les données du modèle supplémentaire      indexes :caracteristiquetests, type: 'nested' do        indexes :id,   type: 'integer'        indexes :piscine, type: 'string'        indexes :barbecue, type: 'string'        indexes :camping_id, type: 'integer'      end  end      def as_indexed_json(options = {})      self.as_json(only: [:name, :adresse, :code_postale, :commune, :description, :nomdep, :nomregion, :latitude, :longitude, :etoile, :caracteristiquetest_id],      include: {caracteristiquetest: {only: [:id, :piscine, :barbecue, :camping_id]}})    end      class << self      def custom_search(query)        __elasticsearch__.search(query: multi_match_query(query),  aggs: aggregations)      end        def multi_match_query(query)        {          multi_match: {            query: query,            type: "best_fields",             fields: ["name^6", "nomdep^10", "commune^8", "nomregion^7"],            operator: "and"          }        }      end  def aggregations    {  query: {    bool: {      must: [        {term:          {caracteristiquetest.barbecue : "non"}}]    }   }  }      end    end  

homesearch.html.erb

<div class="container">      <div class="row">          <div class="search">                     <%= form_tag(result_path, method: :get) %>                          <%= text_field_tag :q, params[:q], class:"search-query form-control" %>                    <%= submit_tag "GO", class:"btn btn-danger", name: nil %>          </div>       </div>  </div>  

Rails Associations don't work

Posted: 31 Aug 2016 06:56 AM PDT

I've read through many tutorials, and copied their code exactly, yet what they claim works for them doesn't work for me.

I'm making a most basic "has_many" and "belongs_to" association, but rails refuses to acknowledge any association whatsoever.

A user "has_many" emails. Emails "belong_to" user. Here's my code:

user.rb

class User < ActiveRecord::Base    unloadable      has_many :emails    accepts_nested_attributes_for :emails,      :allow_destroy => true,    #  :reject_if     => :all_blank  end  

email.rb

class Email < ActiveRecord::Base    unloadable      belongs_to :user  end  

Then, in the console:

User.emails.build  NoMethodError: undefined method `emails' for #<Class:0x00000006c16e88>  

Indeed, this "NoMethodError" persists no matter what.

As of now, my guess is that a capacitor in my hardware burnt out while I was installing rails, causing everything to work except this one thing. Or maybe it's something else :p

EDIT:

Another console attempt:

my_user = User.new  my_user.emails.build  

Also results in an undefined "emails" method.

I noticed that my original user class has a bad comma at the end; removing that, I get this error:

ActiveRecord::UnknownAttributeError: unknown attribute 'user_id' for Email.  

Metasploit Update: Error In Bundle Install ( nokogiri 1.6.8 )

Posted: 31 Aug 2016 06:01 AM PDT

Metasploit was working Fine until this morning I updated it with msfupdate, And all went to shit.

Typing msfconsole Now gives me this error:

Could not find nokogiri-1.6.8 in any of the sources Run bundle install to install missing gems.

So I went and Typed bundle install, It was going fine until this happened:

Installing nokogiri 1.6.8 with native extensions  Gem::Ext::BuildError: ERROR: Failed to build gem native extension.  /usr/bin/ruby2.2 -r ./siteconf20160831-24032-1wim46x.rb extconf.rb --use-system-libraries  Using pkg-config version 1.1.7  checking if the C compiler accepts ... yes  Building nokogiri using system libraries.  checking for libxml-2.0... no  checking for libxslt... no  checking for libexslt... no  ERROR: cannot discover where libxml2 is located on your system. please make sure pkg-config is installed.  * extconf.rb failed *  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:      --with-opt-dir      --without-opt-dir      --with-opt-include      --without-opt-include=${opt-dir}/include      --with-opt-lib      --without-opt-lib=${opt-dir}/lib      --with-make-prog      --without-make-prog      --srcdir=.      --curdir      --ruby=/usr/bin/$(RUBY_BASE_NAME)2.2      --help      --clean      --use-system-libraries      --with-zlib-dir      --without-zlib-dir      --with-zlib-include      --without-zlib-include=${zlib-dir}/include      --with-zlib-lib      --without-zlib-lib=${zlib-dir}/lib      --with-xml2-dir      --without-xml2-dir      --with-xml2-include      --without-xml2-include=${xml2-dir}/include      --with-xml2-lib      --without-xml2-lib=${xml2-dir}/lib      --with-libxml-2.0-config      --without-libxml-2.0-config      --with-pkg-config      --without-pkg-config      --with-pkg-config      --without-pkg-config      --with-override-variables      --without-override-variables      --with-xslt-dir      --without-xslt-dir      --with-xslt-include      --without-xslt-include=${xslt-dir}/include      --with-xslt-lib      --without-xslt-lib=${xslt-dir}/lib      --with-libxslt-config      --without-libxslt-config      --with-pkg-config      --without-pkg-config      --with-exslt-dir      --without-exslt-dir      --with-exslt-include      --without-exslt-include=${exslt-dir}/include      --with-exslt-lib      --without-exslt-lib=${exslt-dir}/lib      --with-libexslt-config      --without-libexslt-config      --with-pkg-config      --without-pkg-config    extconf failed, exit code 1    Gem files will remain installed in /usr/share/metasploit-framework/vendor/bundle/ruby/2.2.0/gems/nokogiri-1.6.8 for inspection.  Results logged to /usr/share/metasploit-framework/vendor/bundle/ruby/2.2.0/extensions/x86-linux/2.2.0/nokogiri-1.6.8/gem_make.out  Using rack-test 0.6.3  Using faraday 0.9.2  Using jsobfu 0.4.1  Using packetfu 1.1.11  Using rex-arch 0.1.1  Using rex-ole 0.1.2  Using rex-random_identifier 0.1.0  Using rex-zip 0.1.0  Using simplecov 0.12.0  Using activesupport 4.2.7.1  Using tzinfo-data 1.2016.6  An error occurred while installing nokogiri (1.6.8), and Bundler cannot  continue.  Make sure that gem install nokogiri -v '1.6.8' succeeds before bundling.  

So I started Searching and stuff, Came across This, suggested that I should run: bundle config build.nokogiri --use-system-libraries

But again..Nothing. I also tried gem install nokogiri -v 1.6.8, Even older versions gem install nokogiri -v 1.6.0.

I'm using Kali.

Thanks In Advance!

Can't create a route that has a segment with a leading dot in Rails (to verify Let's Encrypt)

Posted: 31 Aug 2016 05:58 AM PDT

In my Rails 5 app on Heroku, I'm trying to create a route for this URL: http://beta.example.com/.well-known/acme-challenge/some-key, so I can verify my server with Let's Encrypt to get an SSL certificate. But I can't get the route to work with a leading dot or period in any segment of the route, it just returns 404 Not Found.

In other words, the dot at the beginning of .well-known is screwing things up. I can get a route to work without the dot, or if the dot is somewhere else (e.g. well.known), but if the dot is the first character in the segment, it doesn't work.

I started with this:

get "/.well-known/acme-challenge/:id" => "pages#letsencrypt"  

When that didn't work, I tried using a (dynamic segment):

get ':letsencrypt_route/acme-challenge/:id', to: "pages#letsencrypt", letsencrypt_route: /[^\/]+/  

This will allow a dot anywhere in the segment... except as the first character, which is where I need it.

Any idea what's causing this? When I try and navigate to a URL that has a leading dot in a segment, it doesn't even show anything in my log, it's just an immediate 404.

I've seen some people having this issue on both Rails 4 and Rails 5, and it's happening for me using either Thin or Puma, and in both development and production. I've also tried using a couple of the letsencrypt gems, but it stalls at the same point.

Here is my Gemfile with the gems in both environments:

source "https://rubygems.org"    ruby "2.3.1"    gem "rails", "5.0.0.1"    gem "pg", "0.18.4" # postgresql database  gem "twitter-bootstrap-rails", "~> 3.2.2"    gem "active_median", "~> 0.1.0" # used with chartkick for graph reporting  gem "activerecord-session_store", require: false # save session to database  gem "acts-as-taggable-on", git: "https://github.com/mbleigh/acts-as-taggable-on" # tagging  gem "administrate", git: "https://github.com/heyogrady/administrate", branch: "rails5"  gem "analytics-ruby", "~> 2.0.0", require: "segment/analytics" # segment.io  gem "arel"  gem "autoprefixer-rails" # for CSS vendor prefixes  gem "bootbox-rails", "~>0.4" # wrappers for javascript dialogs  gem "bootstrap-switch-rails" # bootstrap-switch.js  gem "bourbon"  gem "bower-rails" # install front-end components  gem "browser" # For variants support  gem "carrierwave" # for handling file uploads  gem "carmen-rails" # country and region selection  gem "chartkick", "~> 1.2.4" # used to provide nice looking charts  gem "chronic" # natural language date parser  gem "codemirror-rails", ">= 5.11" # display source code in pattern library  gem "coffee-rails", ">= 4.1.1"  gem "coffee-script-source", ">= 1.8.0" # Coffee script source  gem "country_select" # HTML list of countries  gem "dalli" # for memcached  gem "delayed_job_active_record", ">= 4.1" # background job processing  gem "delayed_job_web", ">= 1.2.10" # web interface for delayed job  gem "devise", ">= 4.2.0"  gem "devise-async", git: "https://github.com/mhfs/devise-async", branch: "devise-4.x" # for user authentication  gem "flamegraph" # super pretty flame graphs  gem "fog", require: false # for handling s3  # gem "font_assets" # Handle Cross-Origin Resource Sharing on fonts  gem "font_assets", git: "https://github.com/ericallam/font_assets", ref: "457dcfddc4318e83679e9a0935612924b7717085"  gem "friendly_id", "~> 5.1.0"  gem "fullcontact" # social profile info from fullcontact.com  gem "fuzzy_match" # used by smart_csv_parser for contact & address mapping  gem "google-api-client", "< 0.9", require: "google/api_client" # connecting to Google API  gem "groupdate", "~> 2.1.1" # used with chartkick for graph reporting  gem "handy", git: "https://github.com/heyogrady/handy"  gem "hike" # finds files in a set of paths  gem "honeybadger" # for error tracking  gem "intercom-rails" # tracking user behavior  gem "jbuilder", ">= 2.4.1" # for building JSON  gem "jquery-fileupload-rails", "~> 0.4.6" # file uploads  gem "jquery-rails" # jQuery  gem "jquery-ui-rails" # jQuery UI  gem "json" # for parsing JSON  gem "kaminari" # pagination  gem "le" # logentries  gem "less-rails", ">= 2.7.1" # LESS => CSS  gem "lograge" # better log formatting  gem "mandrill-api" # sending and tracking emails  gem "mechanize" # for screen scraping  gem "memory_profiler" # lets us use rack-mini-profilers GC features  gem "mini_magick" # processing images  gem "newrelic_rpm" # monitor app performance  gem "nylas", "1.1.0" # emails, calendar, contacts via Nylas.com  gem "oink"  gem "omniauth" # third party authentication  gem "omniauth-google-oauth2" # Google authentication  gem "omnicontacts" # retrieve contacts from email providers  gem "open_uri_redirections" # allow OpenURI redirections from HTTP to HTTPS  gem "paper_trail" # maintain record of stripe plans & subscriptions  gem "prawn-labels" # PDF labels  gem "puma" # server  gem "public_activity" # for model activity tracking  gem "rack-mini-profiler", require: false # display page load time badge  gem "rack-timeout" # raise error if Puma doesn't respond in given time  gem "rack-zippy" # serve gzipped assets  gem "rails-deprecated_sanitizer" # Our app uses old sanitizer methods.  gem "react-rails", "~> 1.6.0"  gem "responders", "~> 2.0" # respond_with and respond_to methods  gem "rest-client"  gem "sass-rails", ">= 5.0.3"  gem "semantic-ui-sass", git: "https://github.com/heyogrady/semantic-ui-sass"  gem "select2-rails" # select/search/dropdown box  gem "selenium-webdriver", require: false # screen-scraping  gem "signet"  gem "simple_form", ">= 3.2.1" # forms made easy for rails  gem "sinatra", git: "https://github.com/sinatra/sinatra"  gem "stripe", "~> 1.15.0" # charging customers  gem "stripe_event" # Stripe webhook integration  gem "stackprof" # a stack profiler  gem "state_machines-activemodel", ">= 0.4.0.pre"  gem "state_machines-activerecord", ">= 0.4.0.pre"  gem "toastr-rails" # display toaster notifications  gem "therubyracer", platforms: :ruby  gem "turbolinks", "~> 5.0.0.beta" # faster page loads  gem "twilio-ruby" # phone and SMS services  gem "twitter-typeahead-rails", "~> 0.11.1.pre.corejavascript" # typeahead.js - autocomplete  gem "uglifier", ">= 1.0.3"  gem "uuidtools"  gem "valid_email" # email validation  gem "wicked" # multi-page wizard forms  gem "yaml_db", git: "https://github.com/heyogrady/yaml_db", branch: "monkey-patch-rails-5" # import/export yml->db  gem "yaml_dump", git: "https://github.com/vanboom/yaml_dump" # dump db records to yaml files  # gem "zeroclipboard-rails", "~> 0.1.1" # copy to clipboard  

How to add custom field to devise forgot my password?

Posted: 31 Aug 2016 06:02 AM PDT

Let me preface this with I am a Java developer, but my team is developing an SSO microservice for our product in rails so I am learning as I go.

Currently I have it setup to send a confirmation of password reset when a user enters their email into this form:

<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %>  <%= devise_error_messages! %>      <div class="row">          <div class="medium-12 small-12">              <div class="field">                  <%= f.label :email, class: 'field-label' %>                  <%= f.email_field :email, autofocus: true %>              </div>          </div>      </div>        <div class="row">          <div class="actions columns medium-12 small-12">              <%= f.submit "Send", id: "send-button" %>          </div>      </div>        <div class="row text-center align-center">          <div class="small-8 small-centered columns">              <br><p id="form-subheading">* For security reasons, we do NOT store your password. We will NEVER send your password via email.</p>          </div>      </div>  <% end %>  

And it successfully passes through the following function in the class Users::PasswordsController < Devise::PasswordsController

# POST /resource/password  def create   super  end  

The problem is now we need to add the following first_name and last_name fields to the form, and authenticate it against the User model before sending form to their email, but it is ignoring those parameters entirely. Clearly I need a check somewhere, but have no idea where to begin.

<div class="row">      <div class="medium-5 small-12">          <div class="field">              <%= f.label :first_name, class: 'field-label' %>              <%= f.text_field :first_name %>          </div>      </div>      <div class="medium-6 medium-offset-1 small-12">          <div class="field">              <%= f.label :last_name, class: 'field-label' %>              <%= f.text_field :last_name %>          </div>      </div>  </div>  

I know they get sent to the backend because the params[:user] variable contains the information if I put a byebug statement in the function. I am just unsure how to validate the new information in the form.

Any help on building custom fields for this form would be appreciated.

Fetch Gmail, Yahoo, Hotmail contacts with pagination using OmniContacts

Posted: 31 Aug 2016 05:42 AM PDT

I'm using OmniContacts to integrate with Gmail, Yahoo, Hotmail APIs. But It's fetching all contacts of account. Some users have more than 1000 contacts.

So, I need to add pagination to send request to the API. In Gmail the gem has limit as this importer :gmail, "xxx", "yyy", :max_results => 1000. But I need to add pagination not limit.

How can I send request with pagination for Gmail API, and (Yahoo, Hotmail) APIs?

Automatic state transition after certain period of time

Posted: 31 Aug 2016 05:26 AM PDT

I am using state machine gem https://github.com/pluginaweek/state_machine.

I want to change a particular state after a certain period of time (say 2 days). Is there a way to automatically change state in background, without using job or scheduler?

Get videos which doesn't have any of given cateogires

Posted: 31 Aug 2016 05:23 AM PDT

I'm trying to get all videos with those parameters. But even tho I don't get any error I still get some videos which have category [17] for example.

  • Doesn't have any of fallowing categories [15,17,26,32,35,36,37]
  • have duration longer then 100
  • They are unique

Video.rb

class Video < ActiveRecord::Base     self.primary_key = "id"     has_and_belongs_to_many :categories  end  

Category.rb

class Category < ActiveRecord::Base      has_and_belongs_to_many :videos  end  

My Query

    @excluded_categories = [15,17,26,32,35,36,37]        @videos = Video.joins(:categories).where("duration >= 100").where.not( categories: { id: @excluded_categories } ).pluck(:video_id).uniq  

Is there better way how to write how write this query?

Rails assets precompile does not generate paths with leading /

Posted: 31 Aug 2016 04:49 AM PDT

I am using sass helpers, background-image: image-url("favicon.png") in my SCSS file.

In dev mode, the background url's are generated with the path

background-image: url(/assets/images/favicon-<uuid>.png);  

However, in production or staging, the background url's are generated with the path

background-image: url(assets/images/favicon-<uuid>.png);  

Notice that production does not have a leading slash. This leads to all kinds of havoc.

What makes image-url generate absolute vs relative path?

Cap deploy assets precompile error

Posted: 31 Aug 2016 04:48 AM PDT

I am setting up new staging server for my application. Existing staging, as well as development environments with the same release versions work fine.

Trying to cap deploy, I receive the following error:

    [1906b0ea] Command: cd /home/user/appname/releases/20160831113756 && ( export RAILS_ENV="production" ; ~/.rvm/bin/rvm 2.3.0 do bundle exec rake assets:precompile )  rake aborted!  ...  Sprockets::FileNotFound: couldn't find file 'datatables' with type 'application/javascript'  Checked in these paths:     /home/user/appname/shared/bundle/ruby/2.3.0/gems/babel-source-5.8.35/lib    /home/user/appname/releases/20160831113756/app/assets/images    /home/user/appname/releases/20160831113756/app/assets/javascripts    /home/user/appname/releases/20160831113756/app/assets/stylesheets    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-datatables-rails-3.3.0/app/assets/images    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-datatables-rails-3.3.0/app/assets/javascripts    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-datatables-rails-3.3.0/app/assets/media    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-datatables-rails-3.3.0/app/assets/stylesheets    /home/user/appname/shared/bundle/ruby/2.3.0/gems/cocoon-1.2.8/app/assets/javascripts    /home/user/appname/shared/bundle/ruby/2.3.0/gems/turbolinks-2.5.3/lib/assets/javascripts    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-rails-4.1.1/vendor/assets/javascripts    /home/user/appname/releases/20160831113756/vendor/assets/bower_components    /home/user/appname/releases/20160831113756/tmp/themes        /home/user/ap  

pname/releases/20160831113756/vendor/assets/bower_components

Here is my application.js file //

= require jquery              //= require jquery_ujs              //= require datatables              //= require turbolinks              //= require cocoon              //= require select2              //= require highcharts              //= require highcharts/highcharts-more              //= require sparklines              //= require rangeslider.js/dist/rangeslider              //= require Sortable              //= require moment              //= require pikaday              //= require tooltipster              //= require urijs              //= require jscolor/jscolor              //= require_tree .  

And here are parts of Gemfile.lock

    jquery-datatables-rails (3.3.0)        actionpack (>= 3.1)        jquery-rails        railties (>= 3.1)        sass-rails     ....         ajax-datatables-rails (0.3.1)        railties (>=   

3.1)

I've searched several SO questions, but none seem to be relevant.

Do you have any ideas on what could cause that and how to solve it?

Run before filter an large number of actions in Ruby on Rails 4

Posted: 31 Aug 2016 05:29 AM PDT

I have lots of controller in my Rails application, and I need to use a before_filter before some actions in different controllers. The before filter will execute the same code of all these actions. Is there a clean DRY way(in application_controller for instance) to specify the list of actions that should run this before_filter? I have tried to use before_filer in all controllers(9), but this looks so repetitive since it is the same code.

God Script is failing to take care of unicorn with Rails application

Posted: 31 Aug 2016 04:37 AM PDT

God Script is failing on line. I have added shell script in /etc/init.d/god-init which runs the god script which is placed in "config/unicorn.god"

pid_file = File.join(RAILS_ROOT, 'tmp/pids/unicorn.pid')    w.name = 'unicorn'  w.interval = 60.seconds  w.start = "unicorn -c #{RAILS_ROOT}/config/unicorn.rb -D"  w.stop = "kill -s QUIT $(cat #{pid_file})"  w.restart = "kill -s HUP $(cat #{pid_file})"  w.start_grace = 20.seconds  w.restart_grace = 20.seconds  w.pid_file = pid_file    w.behaviour(:clean_pid_file)  

This is giving me an error as -

Sending 'load' command with action 'leave'    undefined method `behaviour' for #<God::Watch:0x00000001faa0b8>  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god/task.rb:265:in `method_missing'  /var/www/hamperville/config/unicorn.god:15:in `block in root_binding'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god.rb:294:in `task'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god.rb:281:in `watch'  /var/www/hamperville/config/unicorn.god:3:in `root_binding'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god.rb:593:in `eval'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god.rb:593:in `running_load'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god/socket.rb:58:in `method_missing'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1624:in `perform_without_block'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1584:in `perform'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1657:in `block (2 levels) in main_loop'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1653:in `loop'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1653:in `block in main_loop'  

Can somebody suggest if i am doing something wrong?

Insufficient validation for 'name' using / +\w/. Use \A and \z as anchors

Posted: 31 Aug 2016 04:39 AM PDT

I used brakeman for generating scanning reports in my application. It generated a Format Validation security warning with High Confidence in my model page:

Insufficient validation for 'name' using / +\w/. Use \A and \z as anchors near line 54

This is the line in my model where I am facing error:

validates_format_of :name, :with => / +\w/, :message => "must be your first and last name."  

If there is no space in the name field, I am showing above validation. How can show it \A and\z format?

File Import Modal Issues Rails 5 Bootstrap 3

Posted: 31 Aug 2016 04:19 AM PDT

So it would appear Modals are the bane of my existence lately.

I have gone over previous questions I've asked about modals, tried and tried again but this bugger just wont go.. and I'm getting some wonky server output when i try to just open the modal.

this is what the server is outputting when I click the link that should open the modal.. Note** I want the modal to open from anywhere in the app via the nav-bar.

rails server output:

Started GET "/users/import" for ::1 at 2016-08-31 05:04:14 -0600  **Processing by UsersController#show as JS** **<-- ODD AS IM NOT CALLING SHOW AT ALL.**    Parameters: {"id"=>"import"}    User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]    User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."user_ident" = $1 LIMIT $2  [["user_ident", "import"], ["LIMIT", 1]]    CACHE (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."user_ident" = $1 LIMIT $2  [["user_ident", "import"], ["LIMIT", 1]]    Rendering users/show.html.erb within layouts/application    Rendered users/show.html.erb within layouts/application (12.4ms)  Completed 500 Internal Server Error in 41ms (ActiveRecord: 0.6ms)        ActionView::Template::Error (undefined method `role' for nil:NilClass):      1: <p>      2:   <strong>Role:</strong>      3:   <%= @user.role.name %>      4: </p>      5:      6: <p>    app/views/users/show.html.erb:3:in `_app_views_users_show_html_erb__3994365900320744804_70230998256260'    Rendering /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb    Rendering /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb    Rendered /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.6ms)    Rendering /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb    Rendered /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.8ms)    Rendered /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb (34.7ms)  DEPRECATION WARNING: #original_exception is deprecated. Use #cause instead. (called from status_code_with_paginate at /Users/developer/.rvm/gems/ruby-2.3.1/gems/will_paginate-3.1.0/lib/will_paginate/railtie.rb:49)  

the strange thing here is that im not calling the show action at all but im seeing in the second line of the server out put its using it for some reason.

here is the import.js controller action

  def import      User.import(params[:file])      redirect_to users_path, notice: 'Users Added Successfully'    end  

and its user.rb model method.

  def self.import(file)      CSV.foreach(file.path, headers: true) do |row|        User.create! row.to_hash      end    end  

my navbar link:

<li><%= link_to "Import Users", import_users_path, remote: true %></li>  

and for now (as I just want to open the thing and i can handle the create.js) here is the import controller action (import.js.erb) -- that I thought would handle opening the modal.

$("#userImport").modal('show');  

perhaps I'm way off here but i dont see why this would be different from a standard modal with a form..??

any help is greatly appreciated.

EDIT # 1 - Adds Routes.rb and rake routes output

  resources :users do      collection {post :import}    end        import_users POST   /users/import(.:format)           users#import             users GET    /users(.:format)                  users#index                   POST   /users(.:format)                  users#create          new_user GET    /users/new(.:format)              users#new         edit_user GET    /users/:id/edit(.:format)         users#edit              user GET    /users/:id(.:format)              users#show                   PATCH  /users/:id(.:format)              users#update                   PUT    /users/:id(.:format)              users#update                   DELETE /users/:id(.:format)              users#destroy  

Rails_Admin and carrierwave multiple upload (rails 4)

Posted: 31 Aug 2016 04:11 AM PDT

I was using the Gem Administrate and decided to change for Rails_Admin. Since I have changed, almost everything work well except that I cannot upload multiple images ?

How comes? Anyone knows how to fix this? As everything worked fine... I don't know what piece of code to post, so please just ask me what would be needed :)

Thanks

Rails: mounting engine inside nested routes

Posted: 31 Aug 2016 03:58 AM PDT

I am trying to mount an engine at two different points in the same app.

The first point, which is working, is at the root level 'localhost:3000/news'.

The second is one resource deep, with the desired url structure something like this: 'localhost:3000/venues/1/news'. This is not working.

I am initialising the engine in the host app routes file like this

  mount NewsEngine::Engine => "/"     resources :venues do      mount NewsEngine::Engine => "/"     end  

Running rake routes however only yields the first level of routes.

newsitems GET  /news(.:format)              news_engine/newsitems#index                                          newsitem GET  /news/:newsitem_id(.:format) news_engine/newsitems#show   

Weirdly, referencing even the first level raises an error:

=link_to "News", intertain_news_engine.newsitems_path  => No route matches {:action=>"index"} missing required keys: [:venue_id]  

I would have expect this error trying to call venue_newsitems_path but not newsitems_path

The routes file in the engine itself looks like this.

NewsEngine::Engine.routes.draw do    resources :newsitems, param: :newsitem_id,                          only: [:index, :show],                          path: 'news'    end  

Venues are retrieved using config blocks in the host application that tell the engine to call a before_action method from the host app application controller - though I can't see how this would be a problem as it currently seems solely down to the routing.

Automatically send push notification in rails

Posted: 31 Aug 2016 04:10 AM PDT

I want to automatically send a push notification when ever the database record is updated. The push notifaction is for an android device. The records are from a Ruby on Rails application.

Any help will be appreciable .Thanks in advance.

Tuesday, August 30, 2016

using data-rel tag, link to a div in dinamically process with Ruby on Rails | Fixed issues

using data-rel tag, link to a div in dinamically process with Ruby on Rails | Fixed issues


using data-rel tag, link to a div in dinamically process with Ruby on Rails

Posted: 30 Aug 2016 08:38 AM PDT

I want to do a Facybox, using this method in the tutorial : http://sohtanaka.developpez.com/tutoriels/javascript/creez-fenetre-modale-avec-css-et-jquery/fichiers/

The problem is that the "data-rel" tag seems to don't work in dinamically circumstances. here is my code:

  <div class="row prod">      <% @type1.each do |product| %>        <div class="product-tile">          <div class="entry col-xs-2 col-xs-offset-0 col-sm-4 col-sm-offset-0 col-md-4 col-md-offset-0 col col-lg-4 col-lg-offset-0 col">            <h3><%= product.title %></h3>            <div class="product_img img-responsive">              <%= image_tag(product.image_url, :class => 'the_img') %>              <a href="#" data-width="1000" data-rel="popup1" class="poplight discover">Discover</a>               <h3><%=product.title%></h3>                <div id="popup1" class="popup_block">  	               <h3><%=product.title%></h3>                   <%= image_tag(product.image_url, :class => 'the_img') %>  	                <p>Soh Tanaka est traduit sur developpez.com.</p>                </div>            </div>            <div class="product_description">              <%= sanitize(product.description)%>              <div class="price_line">                <span class="price"><%=number_to_currency(product.price)%></span>              </div>            </div>          </div>        </div>      <%end%>    </div>

The <%=product.title%> and <%product.image_url%> gives me always the same result : the first occurrence from my database. how could I fix it? Thanks!

Rails file_filed doesn't pass params

Posted: 30 Aug 2016 08:25 AM PDT

I have trouble with my image update

My form

  = form_for @user, :html => {class: "form form_profile"} do |user|      = user.file_field :avatar   .... other fields    end   

and controller update and user_avatar_params action

def update   respond_to do |format|         # binding.pry        if params[:user][:avatar]            if current_user.update(user_avatar_params)            flash[:notice] = 'Updated            format.html { render action: 'edit' }            format.js { render 'success_edit', layout: false }   ....  end           def user_avatar_params      params.require(:user).permit(:avatar)   end  

my params from console

{"utf8"=>"✓", "_method"=>"patch", "user"=>{"current_password"=>"", "password"=>""}, "action"=>"update", "controller"=>"users", "id"=>"2"}  

i use paperclip

What wrong with it?

Rails 4 API, how to create a URL from a JSON response?

Posted: 30 Aug 2016 08:42 AM PDT

I'm working on an API where I have a few routes setup, ie

http://localhost:3000/phone_number_lookup/1234567890

which can return a JSON response like so:

{  "AccountCode": "1234",  "AccountID": 13579,  "BalanceCurrent": "5000",  "Phone": "1234567890",  "Id": 123123,  "SerialNumber": "Y2K2000XY2016",  "MACADDRESS": "y2k2000xy2016",  "EQUIPMENTTYPE_Name": "Motorola DCX100 HD DVR",  "ADDRESS_Zip": "90210",  "ItemID": 12345,  "iVideoSystemID": 1000001  "id": null  }  

The next 'step' of the API consumption would be, 'given the initially returned response, use 4 of those parameters and pass them into a remote URL that will then do something.'

Like so:

http://myremoteURL.com/Service/Param1?=sSerialNumber&Param2=iVideoSystemID&Param3=sMAC&Param4=ItemID

It would be one thing to just set up a route that takes 4 parameters, but the route needs to be contingent on what the initial JSON response was.

What is the proper way to do this?

Why won't my Angular app send params to my Entangle rails controller?

Posted: 30 Aug 2016 08:16 AM PDT

In an effort to learn about realtime apps, I am trying to create a basic messageboard using Entangled.

I have an Angular app and a Rails backend with a Messages Controller that includes Entangled::Controller. This Rails controller successfully receives a request when a form is submitted from the Angular app - the form is submitted using Entangled. (On clicking submit, a function is triggered in an Angular controller which should create a new message in the backend and update all clients subscribed to that backend.)

I know the Angular function is being triggered on clicking submit, and I know the function receives the correct information from the form: console.log($scope.message) displays {socket: "ws://message-board-olliehm.c9users.io:8080/messages", username: "ggg", content: "gggggg"} where I submit "ggg" in the username field and "gggggg" in the content field.

The problem is that these fields are not arriving at the Rails controller. When I click submit, the correct action is triggered in the Rails controller, but the params don't contain the right information: p params in def create returns {"controller"=>"messages", "action"=>"create"}, with no "message" hash and no "username" or "content" keys.

I cannot work out what Entangled is doing with the username and content fields.

Redis is new to me so I'm not sure if the problem is there. I have Redis installed and the redis-server is running as required by Entangled. I have a redis initializer as below, which in the Rails console is successfully connecting and letting me put data in the database:

$redis = Redis.new(:host => $IP, :port => 6379)  

Here's my Angular controller:

var controllers = angular.module('controllers');    controllers.controller('MessageboardController', ['$scope','Message', function($scope,Message){      $scope.message = Message.new();      $scope.post = function() {      console.log($scope.message);      $scope.message.$save(function() {        $scope.$apply(function() {          $scope.message = Message.new();        });      });    };      Message.all(function(err, messages) {      $scope.$apply(function() {        $scope.messages = messages;      });    });    }]);  

Message here refers to this factory:

messageboard.factory('Message', function(Entangled){    return new Entangled('ws://message-board-olliehm.c9users.io:8080/messages');  });  

And here's my Angular view:

<h1>Messageboard</h1>    <section class='row' ng-if='messages'>    <ul>      <li ng-repeat='message in messages'>        {{messages.username}}        {{messages.content}}      </li>    </ul>  </section>    <section class='row'>    <form ng-submit="post()">      <div class='form-group'>        <label for='username'>Message as</label>        <input ng-model='message.username' name='username' type='text'>      </div>      <div class='form-group'>        <input ng-model='message.content' name='message' type='text' placeholder='Write your message here'>      </div>      <div class='form-group'>        <input type="submit">      </div>    </form>  </section>  

Advice would be hugely appreciated - this has caused prolonged frustration and I'm very keen to get stuck into creating something with realtime updates.

Rails Mailer does not pick up on the host

Posted: 30 Aug 2016 08:04 AM PDT

Site is in sub-directory /app

In development.rb:

config.action_mailer.default_url_options = { host: 'localhost:3000/app' }

Url generated in the mailer item_url(1):

localhost/item/1, it should be: localhost:3000/app/item/1

How to replace localhost with localhost:3000/app?

Rails: 4.1.15

How do I save a carrierwave original image as a png but all versions as jpg?

Posted: 30 Aug 2016 07:57 AM PDT

The original image that is uploaded is a png file with transparency. Upon upload, I would like to create multiple versions, all jpg filing in the transparency with white background, but keep the original as a png.

The file names are UUID'd for CDN which will be enabled once I figure this out. I have used the recommended method for UUID per carrierwave docs and attempted to modify for my specific case.

The uploader included below successfully uploads to s3. The hashed files appear to be correctly named -- they contain a hash as well as the correct extension.

  • 123-456-789.png
  • web_123-456-789.jpg

Error 1

Images are stored in the db incorrectly. If I enter the rails console and attempt to output the image url the extension is '.png' even though the uploaded file in s3 is a '.jpg'

product.primary_image.recreate_versions!  product.save!  product.primary_image.web.url => https://../web_123-456-789.png  

Error 2

Looking at the file web_123-456-789.jpg in s3 and clicking 'properties' shows the content-type is 'image/png' I am using Carrierwave 0.11.2 so content-type is supposed to be set for me was my understanding.

Uploader file

# encoding: utf-8  class PrimaryUploader < CarrierWave::Uploader::Base    include CarrierWave::MiniMagick      storage :fog      def store_dir      "#{model.class.to_s.underscore.pluralize}/#{model.product_number}/claw"    end      version :web do      process resize_and_pad: [400, 400, '#FFFFFF', 'Center']      process convert: 'jpg'    end      ... other similar versions ...      def filename      if version_name != nil        ext = "jpg"      else        ext = "png"      end      "#{secure_token}.#{ext}" if original_filename.present?    end      protected      def secure_token      var = :"@#{mounted_as}_secure_token"      model.instance_variable_get(var) || model.instance_variable_set(var, SecureRandom.uuid)    end  end  

Rails5 - Ordering with Class method and params

Posted: 30 Aug 2016 07:38 AM PDT

In Rails, I want to order some tweets by number of likes desc using paramsand I am stuck..

I wrote a simple Class method in my model:

class Twit < ApplicationRecord    def self.most_liked   order(like: :desc)  end    end  

And here is my method in my controller:

class TwitsController < ApplicationController     def index    if params[:filter]     @twits = Twit.most_liked(params[:filter])    else     @twits = Twit.all    end   end    end  

If I only use @twits = Twit.most_liked, it works fine, but when I add my condition with params it fails.

Thank you !

Access the radio-button from rails form in javascript

Posted: 30 Aug 2016 07:33 AM PDT

I am building a rails app. I would like to access the radio_button value in Java Script(in document.getElementById). Below is the code snippet from the form.html.erb. Kindly let me know on how to access the same. I tried a lot of options. But nothing worked.

<div class="field">    <div class="container-fluid">      <div class="row">        <div class="col-md-6">          <div class="col-md-4">            <%= "Yet to start" %>            <%= radio_button("development_activity", "progress", "Yet to start", :checked => true) %>          </div>          <div class="col-md-4">            <%= "In Progress" %>            <%= radio_button("development_activity", "progress", "In Progress") %>          </div>          <div class="col-md-4">            <%= "Completed" %>            <%= radio_button("development_activity", "progress", "Completed") %>          </div>        </div>      </div>    </div>  </div>

Rails singleton client lost after a Rails crash

Posted: 30 Aug 2016 07:28 AM PDT

I have several third party APIs I need to connect to, so I have defined an abstract module for Singleton behavior, and the specific connector singleton isntances.

My problem : everytime the Rails server crash (500 error, localhost), it seems I'm losing the @client instance variable of the connector

module ServiceConnector    extend ActiveSupport::Concern      included do      include Singleton      @activated = false      @activation_attempt = false      @client = nil        def client        @client      end        def service_name        self.class.name.gsub('Connector', '')      end        def activate        @activation_attempt = true        if credentials_present?          @client = service_client          @activated = true        end        status_report      end    class MyConnector    include ServiceConnector    @app_id = nil    @api_key = nil      def credentials_present?      @app_id.present? and @api_key.present?    end      def service_client      ::MyService::Client.new(        app_id: @app_id,        api_key: @api_key      )    end      def set_credentials(id, key)      @app_id = id      @api_key = key    end  

I initialize my singleton in a Rails initializer

#config/initializers/my_connectors.rb  my_service = MyConnector.instance  if my_service_should_be_activated?    my_service.set_credentials(      Rails.application.secrets.app_id,      Rails.application.secrets.api_key    )    my_service.activate  end    def some_action_on_client    client.push_event(...)  end  

The set of events

rails s  ...  # MyConnector client Online and working fine  ...  # error 500 on some controller  # (next client request)  # MyConnector @client variable mysteriously set to nil  

Apply css on form collection

Posted: 30 Aug 2016 08:27 AM PDT

I'd like to apply this style on my collection :

  .tag-wrapper      %ul        %li.class_1.class_2         = tag.name  

This is my current code with the collection I'd like to style (see the end of the form) :

 = simple_form_for @recipe, html: {multipart: true} do |f|    - if @recipe.errors.any?      #errors        %p          = @recipe.errors.count          prohibited this recipe from being saved:        %ul          - @recipe.errors.full_messages.each do |message|            %li= message    .row      .panel-body        = f.input :title, input_html: {class: 'form-control'}        = f.input :description, placeholder: 'Dites nous ce que vous aimez dans cette recette ? où l\'avez-vous découverte ? avec quoi l\'accompagnée vous ? ...', input_html: {class: 'form-control'}        = f.input :image, input_html: {class: 'form-control'}          .tag-wrapper          = f.input :my_field, :as => :check_boxes, :collection => @tags.map{|tag| tag.name}  

I don't know how to manage collection. I should isolate each tag to display it in li then add it class_1 and class_2 but I don't know how. Here is the output if it coud help

Output

.tag-wrapper {      background: white;      width: 500px;      margin: 0 auto;      margin-top: 30px;      padding: 30px 40px;      text-align: center;      border-radius: 5px;      box-shadow: 0px 3px 3px 0px rgba(50, 50, 50, 0.4);  }    * {      margin: 0;      padding: 0;  }    * {      -webkit-box-sizing: border-box;      -moz-box-sizing: border-box;      box-sizing: border-box;  }    * {      margin: 0;      padding: 0;  }    * {      -webkit-box-sizing: border-box;      -moz-box-sizing: border-box;      box-sizing: border-box;  }  user agent stylesheetdiv {      display: block;  }
<div class="tag-wrapper">    <div class="input check_boxes optional recipe_all_tags">           <label class="check_boxes optional">All tags</label>      <span class="checkbox">        <label for="recipe_all_tags_vgtalien">          <input class="check_boxes optional tag fa fa-plus" type="checkbox" value="Végétalien" name="recipe[all_tags][]" id="recipe_all_tags_vgtalien" aria-hidden="true">Végétalien        </label>      </span>      <span class="checkbox">        <label for="recipe_all_tags_sans_lait">          <input class="check_boxes optional tag fa fa-plus" type="checkbox" value="Sans_lait" name="recipe[all_tags][]" id="recipe_all_tags_sans_lait" aria-hidden="true">Sans_lait        </label>      </span>    </div>  </div>

Rails not passing the DB Query on search form

Posted: 30 Aug 2016 07:21 AM PDT

Here what looks better, this is the log, its passing the param, but its not passing a query with that param

Started GET "/items?utf8=%E2%9C%93&search=blanca" for 65.34.251.106 at 2016-08-30 03:55:51 +0000  Processing by ItemsController#index as HTML  Parameters: {"utf8"=>"✓", "search"=>"blanca"}  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1  [["id", 3]]  Item Load (0.3ms)  SELECT  "items".* FROM "items" LIMIT 50 OFFSET 0  Item Load (0.2ms)  SELECT  "items".* FROM "items"  ORDER BY "items"."id" ASC LIMIT 1 OFFSET 0  Rendered items/_items.html.erb (3.2ms)  Rendered items/index.html.erb within layouts/application (4.9ms)  

This is the controller:

def index   @items = Item.search(params[:search])  end  

and this is the model:

def self.search(search)   Item.where("nombre LIKE ?", "%#{search}%")  end  

and the search form in the view:

<%= form_tag items_path, :method => 'get', :id => "items_search" do %>   <p>    <%= text_field_tag :search, params[:search], class: "form-control" %>    <%= submit_tag "Search", :name => nil, class: "btn btn-danger" %>   </p>    <div id="items"><%= render 'items' %>  </div>  <% end %>   

I have a _items.html.erb file which has the items to render, that part works because no matter my input on the search bar, it always shows all the items

How to store global api keys in Rails

Posted: 30 Aug 2016 07:35 AM PDT

I have a global api key for authenticating the requests to my server's api.

So the api key has to be stored somewhere in my rails application or on the server.

After a quick search, most people seem to recommend to store your keys in a .yml file and load it in your application. They claim that this is safe because the .yml file is not checked to git/source control.

Obviously you should add the .yml file to the .gitignore, otherwise it will be added git.

But If you do that, then how can the file be loaded after deployment(capistrano) if the .yml file isn't checked in to git and doesn't exist on the server?

Here is an example railscast that demonstrates storing the keys in .yml files:

http://railscasts.com/episodes/85-yaml-configuration-file?autoplay=true

Angular not rendering ng-view if cookies are not set

Posted: 30 Aug 2016 07:14 AM PDT

Very simple, but tricky bug.

This are my controller settings:

angular    .module(...)    .config(...)    .config('RealDispatchesRouter')    .controller('RealDispatchesCtrl', RealDispatchesCtrl)    RealDispatchesRouter.$inject = ['$routeProvider', '$locationProvider'];  function RealDispatchesRouter($routeProvider, $locationProvider) {    $routeProvider.when('/', {      templateUrl: '/angular/templates/realDispatches.controller.html',      controller: 'RealDispatchesCtrl',      controllerAs: 'vm',      reloadOnSearch: false    });    $locationProvider.html5Mode(true);  }    RealDispatchesCtrl.$inject = ['User', ...];  function RealDispatchesCtrl(User, ...) {...}  

The problem is that if I erase the only cookie that I see to have registered, called _session_id, from chrome, then the ngView is not rendered:

<div>    <!-- ngView: -->  </div>  

How to stub out Paperclip::AdapterRegistry::NoHandlerError?

Posted: 30 Aug 2016 07:13 AM PDT

I'm unit testing a controller. Looks like some magic goes on with paperclip with nested resources. Whenever upload_attributes: [:asset] is passed in the params, paperclip somehow gets triggered.

How to stub out the paperclip magic whenever the asset attribute is sent in the params?

Controller:

  def create      render json: {}    end      private      def user_upload_params      params.require(:price_patch_upload).permit(        :status,        upload_attributes: [:asset]      )    end  

Controller Spec:

let(:params) do    {      user: {        upload_attributes: { asset: "file" } # change 'asset' to anything else and no error      }    }  end        it "works" do      post :create, params      expect(response).to have_http_status(:created)    end  

Result:

result error

^^^ How to stub this out?

To get values from 2D array

Posted: 30 Aug 2016 07:53 AM PDT

I have used this query to retrieve the dates for one particular user's approved leaves -

LeaveRequest.where(user_id: 6).where(status: 1).pluck(:from_date, :to_date)  

and I'm getting this array as result -

[[Mon, 12 Sep 2016, Fri, 16 Sep 2016], [Tue, 06 Sep 2016, Tue, 06 Sep 2016], [Thu, 01 Sep 2016, Fri, 02 Sep 2016], [Tue, 30 Aug 2016, Wed, 31 Aug 2016]]   

what I want is to fetch all the dates as well as the dates between 12 Sep 2016 and 16 Sep, 2016 (13th 14th and 15th).

Attempting to iterate with ruby thru 4 twitter bootstrap columns

Posted: 30 Aug 2016 07:58 AM PDT

enter link description hereI am attempting to iterate over a post object, and displaying its body attribute in 4 columns, as to behave like so:

<div class='container-fluid'>    <div class='row'>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>    </div>    <div class='row'>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>      <div class='col-lg-3'><%= *post.body* %></div>    </div>  </div>  

I have tried the following:

<div class='container-fluid'>    <% @posts.each_slice(4) do |four_posts| %>      <div class="row">        <% four_posts.each do |post| %>          <div class="col-lg-3">            <%= post.body %>          </div>        <% end %>       </div>     <% end %>   </div>  

The issue I'm having is that the 'body' content is running in to the adjoining column. Does anyone have any recommendations?

ActiveRecord::StatementInvalid in Hr#internal_employee_page

Posted: 30 Aug 2016 07:29 AM PDT

I am learner ruby on rails,I want to join two model(tables). User.rb(users table)

class User < ActiveRecord::Base has_many :offer_letters end  

OfferLetter.rb(offer_letter table)

class OfferLetter < ActiveRecord::Base belongs_to :user end  

HrController(hr_controller.rb)

class HrController < ApplicationController      def internal_employee_page          @employees = OfferLetter.joins(:user).where(:id => :candidate_id)         end  

end

when run my code I got error "Mysql2::Error: Unknown column 'offer_letters.user_id' in 'on clause': SELECT offer_letters.* FROM offer_letters INNER JOIN users ON users.id = offer_letters.user_id WHERE offer_letters.id = NULL"

<div id="job_details">      <% @employees.each do |emp| %>         <%= render partial: "hr/employee_details", locals: {emp: emp} %>      <% end %>                 </div>  

Error in this line : <% @employees.each do |emp| %> So tell me where i am wrong

when i run ruby and rails code in sublime text i get an error [on hold]

Posted: 30 Aug 2016 07:02 AM PDT

here is the error when i wanted to build the project

please tell how to set this problem

C:/test-install/test.rb:1:in <main>': undefined methodput' for main:Object (NoMethodError)

Test Auth0 Login with RSpec in Rails

Posted: 30 Aug 2016 07:00 AM PDT

I'm using Auth0 for authentication in my rails app. I need to write some feature tests for login and signup. I can't seem to find something concrete on how to do this with rspec and capybara.

Tried doing something along the lines explained in this gist but it still doesn't work. If someone has had experience with rspec feature tests with Auth0 I'd appreciate if you would guide me in the right direction.

Thanks!

Customizable Button - Ruby on Rails

Posted: 30 Aug 2016 07:00 AM PDT

My website has several individual pages about courses and I need to create a button with a specific link for each course. I wanted it to show on every course page and want that the link can be changed on the administration framework by all admins and in case there's not a specific link, would show a default link. Any sugestions about how can I make this happen?

I know this probably sounds confusing, apologies for my english.

Thank you!

Rails 4.2 ActionController:BadRequest custom error message

Posted: 30 Aug 2016 07:07 AM PDT

I want to return from my controller if either a validation failed or a parameter is missing with 400 - bad request. So in my controller if have

if params["patch"].nil? then    raise ActionController::BadRequest.new( "The Json body needs to be wrapped inside a \"Patch\" key")  end  

and i catch this error in my Application Controller with:

rescue_from ActionController::BadRequest, with: :bad_request      def bad_request(exception)    render status: 400, json: {:error => exception.message}.to_json  end  

But it seems like i cannot add custom messages when raising ActionController::BadRequest. Because when passing an invalid body the response is only {"error":"ActionController::BadRequest"} and not the hash i provided.

In the console i get the same behaviour. raise ActiveRecord::RecordNotFound, "foo" indeed raises ActiveRecord::RecordNotFound: foo.

But raise ActionController::BadRequest, "baa" results in

ActionController::BadRequest: ActionController::BadRequest

How can i add custom messages to the BadRequest exception?

fetch data from db based on static set in rails

Posted: 30 Aug 2016 07:34 AM PDT

I want to fetch data from db based on static set in rails

{  data: ['data1','data2']  }  

I have a data table with column values from the static data(data model)

id| Name|    1 | data1    2 | data2    3 | data3  

I have another table which is related to the data table and spl_value column(SPL model)

id | data_id | spl_value    1  |   1     |   x    2  |   2     |   x    3  |   2     |   y    4  |   4     |   z  

How do i fetch spl_value from the static data?

The expected Result is

id | Name    | spl_value    1  |   data1 |   x    2  |   data2 |   x    3  |   data2 |   y  

Rails Version is 3

how can i optimise my spreadsheet report generation logic in rails?

Posted: 30 Aug 2016 06:39 AM PDT

Here is the code currently i am using. its taking long time to generate the report. it seams there are so many database queries that are happening in loop in my rails application. how can i reduce my database queries, by refactoring the existing code so that a quick and nicely formatted report i can generate?

def generate_report          @company = company.find("some id")      book = Spreadsheet::Workbook.new        sheet1 = book.create_worksheet :name => 'Report'          if params[:emps] == "Specific Users"       @employees = @company.employees.where("id in (?)", params[:filter_values]).includes(:department).includes(:location)        elsif params[:emps] == "Some Users"       criteria = params[:search_values]       criteria = criteria.split("_").last.to_i       if params[:search] =="Department"         @employees = @company.employees.where("department_id = ?", criteria).includes(:department).includes(:location)       end         if params[:search]=="Location"         @employees = @company.employees.where("location_id = ?", criteria).includes(:department).includes(:location)       end          elsif params[:emps] == "All Users"       @employees = @company.employees.includes(:department).includes(:location)        end             align_center = Spreadsheet::Format.new({                                              :horizontal_align => :centre,                                          })              make_bold = Spreadsheet::Format.new   ({                                               :horizontal_align => :centre,                                              :weight           => :bold,                                              :size             => 8,                                                                                       })              make_bold_color = Spreadsheet::Format.new   ({                                              :horizontal_align => :centre,                                              :weight           => :bold,                                              :size             => 8,                                              :color=> :white,                                              :pattern => 1                                          })        d1 = params[:from_date].to_date        d2 = params[:to_date].to_date        sno = 0        @employees.each_with_index do |emp, i|      i = i + (i*6) if i > 0      sno = sno +  1         sheet1[i+1,0] = sno         sheet1.row(i+1).set_format(0, align_center)          sheet1[i+1,1] = emp.employee_code         sheet1.row(i+1).set_format(1, align_center)          sheet1[i+1,2] = emp.name         sheet1.row(i+1).set_format(2, make_bold)          sheet1[i+1,3] = emp.location.location_name if emp.location # here will this make a new query again  just beacuase i used "if" statement ?           sheet1[i+2,2] = emp.department.department_name if emp.department # here will this make a new query again  just beacuase i used "if" statement ?         sheet1[i+3,2] = emp.post                sheet1.row(i+1).set_format(3, align_center) # how can i remove this formatting statements from this loop? can we format cells with static coding?          sheet1.row(i+1).set_format(4, align_center)         sheet1.row(i+2).set_format(2, align_center)         sheet1.row(i+3).set_format(2, align_center)             sheet1[i+1,4] = "Check-In"          sheet1[i+2,4] = "Check-Out"         sheet1[i+3,4] = "Duration"           sheet1[i+4,4] = "Status"         sheet1[i+5,4] = "Shift_code"               punch_records = emp.in_outs.where('date >= ? and date <= ?', d1, d2)# can i optimise this query with respect to my above queries?         total_days_count = (d2-d1).to_i + 1           punch_records.each_with_index do |punch_rec,j|          if !punch_rec.nil?        sheet1[i+1,j+5] = punch_rec.check_in.in_time_zone(punch_rec.time_zone).strftime("%I:%M %P")    if !punch_rec.check_in.nil?        sheet1[i+2,j+5] = punch_rec.check_out.in_time_zone(punch_rec.time_zone).strftime("%I:%M %P")   if !punch_rec.check_out.nil?      end      sheet1[i+3,j+5] = punch_rec.duration  if punch_rec      sheet1[i+4,j+5] = punch_rec.nil? ? "" : punch_rec.status      sheet1[i+5,j+5] = punch_rec.nil? ? "" : punch_rec.shift_id       end  end  end  

my model associations are like this.

employee has many in_outs, and in_outs belongs to employee.

location has many employees, employee belongs to location.

department has many employees, employee belongs to department.

Rails 5 - ActiveAdmin can't use current_admin

Posted: 30 Aug 2016 06:36 AM PDT

here is my problem:

I need an Admin system for A Ticket System, I already made the User Table via devise and the Admin Table, I juste added Active Admin after already created my own ticket system etc but now I wanna user ActiveAdmin, SO:

I installed it correctly, I can connect with my Admin Table in it, and I just created my "Tickets" part, which gets all my tickets correctly, the tricky part is that I need to get the current_admin to display only the tickets from his service (commercial or technical..), but I can't access the current_admin method as it is defined in the initializer, not the current_admin_user or current_user or whatever the method could be named.

I give you the code needed for good diagnostic:

config/initializer/active_admin.rb:

config.current_user_method = :current_admin    config.authentication_method = :authenticate_admin!  

app/admin/ticket.rb

ActiveAdmin.register Ticket do    config.batch_actions = false      if current_admin.service == "tech"        scope :to_do_tech      scope :in_progress_tech      scope :done_tech    else      scope :to_do_com      scope :in_progress_com      scope :done_com    end          index do      ...      ...      ...  

And That's what raise the error:

undefined local variable or method `current_admin' for #<ActiveAdmin::ResourceDSL:0x007fd4b0c08988>  

I Already saw and tried a bunch of solution which worked for others but I just can't make it works here..

Hope someone have already used it on Rails 5 and could help me cause i'm out of ideas.

How to require jquery-waypoints-rails gem in application.js

Posted: 30 Aug 2016 07:35 AM PDT

My quetion is pretty much that, I can't find a way to require waypoints.js from the gem jquery-waypoints-rails inside my application.js. Thanks in advance.

Database architecture for payment management application

Posted: 30 Aug 2016 06:28 AM PDT

              Items -> ReservationWithItems -> Checkout -> Payment -> User  Course -> Attendes -> RegistrationForCourse -> Checkout -> Payment -> User                                    YearlyFee -> Checkout -> Payment -> User  

I want to create application with handles reservations, yearly fees and training courses in my mountain club. I would like to organize my code to use Checkout class which will collect products like reservation or yearly fee or registration for course and then I will be able to create payment for them.

Below is my idea how to achieve that but I am not sure if I should use polymorphism here.

Db::Item(name:, cost:)    has_many :reservations, through: :reservations_items    Db::ReservationsItems    belongs_to :item    belongs_to :reservation    Db::Reservation(description:, state:, start_date:, end_date:)    has_many :items, through: :reservations_items    belong_to :payable, polymorphic: true    Db::Checkout    has_many :reservations, as: :payable    has_many :yearly_fees, as: :payable    has_one :payment    belongs_to :user    Db::Payment    belongs_to :checkout    -----    Db::YearlyFee(cost:, :year)    belong_to :payable, polymorphic: true  

Are there somewhere best practices or examples for this kind of systems?

How can I return a Json in controller action

Posted: 30 Aug 2016 06:29 AM PDT

I have this function in my controller:

gerencia.pay_charge(params: params, body: payment)  

This function returns:

{"code"=>200, "data"=>{"barcode"=>"03399.75039 21000.000006 74992.301015 6 69020000002250", "link"=>"https://exmaple.com.br/emissao/110276_19_NAEMAL1/A4XB-110276-74992-XILE0", "expire_at"=>"2016-08-30", "charge_id"=>97611, "status"=>"waiting", "total"=>2250, "payment"=>"banking_billet"}}   

How can I send it in json format?

I have the example in php but I don't know how do it in rails.

In php is this:

$payment = $apiGN->payCharge($params, $paymentBody);  echo json_encode($payment);  

Rails filtered parameters

Posted: 30 Aug 2016 06:16 AM PDT

I am migrating my 4.2 app into Rails 5 and I run into a strange problem. When I try to log in via this:

<%= password_field_tag :password %>  

I got [FILTERED] log in server console, but I got params[:pasword] => "*****" in controller. Which is of course not matching password (I am using BCrypt).

password encrypting:

  def encrypt_password(pass)      BCrypt::Engine.hash_secret(pass, password_salt)    end  

When I pass string "*****" into this method I got the same result as if I pass params[:password] there, which means the controller doesn't know about inserted password but gets only 5 asterisks. If I try this on my master branch with Rails 4.2.7 then in controller I can correctly see inserted password (in log there is "[FILTERED]" correctly).

Do I miss some new feature about filtering parameters in Rails 5???

EDIT: I tried

render plain: params.to_yaml  

I got:

--- !ruby/object:ActionController::Parameters  parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess    utf8: "✓"    authenticity_token: 6/qK4IYcTL3lDTLNEICMmrcBhR5FJy6r3QNN5hYXNQTOqrdwtcX5aye4wN3AIz6PSmsMSf6V7/z8fmUo7KUXyQ==    login: doktor    password: "*****"    commit: Přihlaš  permitted: false  

Call method from controller in view (ROR)

Posted: 30 Aug 2016 06:07 AM PDT

I wanna call method from controller in view using the following code:

<%= memmory("#{broker.id}") %>  

but its giving error "undefined method `memmory' for #<#:0xb3bf71e8>"

Wicked PDF not rendering footer when PDF is created in model

Posted: 30 Aug 2016 05:55 AM PDT

I'm using the wicked PDF gem to generate PDFs for my application. I have had some logic in my controller which has been generating PDFs with footers and page numbers for some time.

I need to now generate this PDF in my model and since moving the controller render pdf code to the model, it hasn't been rendering a footer or proper margin.

This is the code in my controller which works:

WickedPdf.new.pdf_from_string(      render  :pdf => "#{@user.id}_#{@paper.data["statementDate"]}",              :template => "statements/monthly_statement_templates/#{@paper_template}",              :footer => { :html => { template: 'statements/monthly_statement_templates/footer.pdf.erb' }},              :title => "#{@paper.data["statementDate"]} Statement",              :locals => { :statement => @paper.data },              :margin => {                :bottom => 20,                :top => 20              }  

I've moved the code to the model. It looks like the following:

av = ActionView::Base.new()  av.view_paths = ActionController::Base.view_paths    # Need these in case the view constructs any links or references any helper methods.  av.class_eval do    include Rails.application.routes.url_helpers    include ApplicationHelper  end    statement_pdf = WickedPdf.new.pdf_from_string(        av.render :pdf => "#{statement.id}",          :template => "statements/monthly_statement_templates/#{statement_template}",          :footer => { :html => { :template => 'statements/monthly_statement_templates/shared/footer.pdf.erb' }},          :locals => { :statement => statement.data },          :margin => { :bottom => 20, :top => 20 }      )  

When comparing the two PDFs all of the data and styles within the template are the same. However, when rendering the PDF from the model it is not including the footer which has some text and page numbers.

My footer is as follows:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">    <head>      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />      <%= stylesheet_link_tag "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" %>      <style type="text/css">        .legal { font-size: 8px; }      </style>      <script>        function number_pages() {          var vars={};          var x=document.location.search.substring(1).split('&');          for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}          var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];          for(var i in x) {            var y = document.getElementsByClassName(x[i]);            for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];          }        }      </script>    </head>      <body onload="number_pages()">      <div class="container">        <div class="row">          <div class="col-xs-12">            <div class="col-xs-9 legal">            </div>            <div class="col-xs-3 pull-right legal">              <small>Page <span class="page"></span> of <span class="topage"></span></small>          </div>        </div>      </div>    </body>  </html>