Thursday, April 28, 2016

ElasticSearch NotFound after purging a collection | Fixed issues

ElasticSearch NotFound after purging a collection | Fixed issues


ElasticSearch NotFound after purging a collection

Posted: 28 Apr 2016 06:59 AM PDT

I have a "live-test" environment for my rails application which lets us test our application with near-real production settings (email are sent for real, etc.)

I have added some buttons to this "live-test" website that lets us quickly purge a collection (ie. remove all documents from a MongoDB collection)

 def purge      if Rails.env.production?        should_not_happen(severity: :armageddon)      else        Company.unscoped do          Company.all.each(&:destroy)        end        Utility.seed        flashy(:info, 'company XXX restored')        redirect_back      end    end  

The problem rises with ElasticSearch. The first time this purge method is called, it works fine, I have some error

Elasticsearch::Transport::Transport::Errors::NotFound in MyController#purge  

If I click refresh several times on my browser, after 2-3 times the request is finally accepted, but then I have the same problem again :

# 1st time executing purge action : Works  # 2nd time : [404] {"found":false,"_index":"professionals-test","_type":"employee","_id":"57221655f5ae457700b464a2","_version":4}  # 3rd time : [404] {"found":false,"_index":"professionals-test","_type":"employee","_id":"57221655f5ae457700b464a5","_version":6}  # 4th time : [404] {"found":false,"_index":"professionals-test","_type":"employee","_id":"57221655f5ae457700b464a7","_version":4}  # 5th Time : Works  # 6th refresh : Again errors....  

I am using AWS ElasticSearch service with the classic elasticsearch ruby gems.

Rails Active Record - find record where the sum of two columns matches criteria

Posted: 28 Apr 2016 06:59 AM PDT

I have a Property model that has rooms and suites columns.

If I want to find all Properties that have rooms > 5, I can easily write:

Property.where("rooms > 5")

But I want to write a query that finds any Properties that have +5 rooms and suites, so it can be 6 rooms and 0 suites, 0 rooms and 6 suites, 3 rooms and 3 suites or any combination. What matters is that rooms + suites > 5.

How would I write such a query?

Get the number of contributors for a repository

Posted: 28 Apr 2016 06:50 AM PDT

Im using the octokit gem and am following this tutorial. Im trying to get the number of contributors for each repository? I have something like this:

<% @repositories.each do |repo| %>      <li>        <p><b><%= repo[:name].capitalize %></b>:         <i><%= repo[:description].capitalize %></i>         <b>[Watchers: <%= repo[:watchers] %>,          Forks: <%= repo[:forks]%>,          Stargazers: <%= repo[:stargazers_count] %>]</b></p>         <p><%= repo[:contributions] %></p>      </li>    <% end %>  

This does not seem to work, any idea?

Is there a way to assert_select an XHR JQuery response in a Rails controller test?

Posted: 28 Apr 2016 06:45 AM PDT

In my controller tests, I have assertions like this

assert_select "input#name"  

This works fine for normal HTML requests but it doesn't work with JQuery. The best I've come up with is

assert response.body.match /<input .*id=\\\"name\\\".*\/>/  

Is there a better way?

Rails Grape routes

Posted: 28 Apr 2016 06:40 AM PDT

I know this is a stupid question, but I need to help

I have project with API on grape.

In my routes.rb i mount API

  mount API::Root => '/'  

in api/api.rb

module API   class Root < Grape::API     prefix 'api'     default_format :json     add_swagger_documentation(        hide_documentation_path: true,        markdown: GrapeSwagger::Markdown::KramdownAdapter     )       mount Home::Users     end  end  

end i have rout like this

POST /api/users/:id

What do I need to make that route was without a prefix 'api'

POST /users/:id

Paperclip video attachment error using paperclip-av-transcoder

Posted: 28 Apr 2016 06:30 AM PDT

I am making a Ruby on Rails application and am trying to allow video files to be uploaded through the application.

I'm using the paperclip gem to handle the attachment of files, paperclip-av-transcoder gem (as suggested) to handle the transcoding. I also have the aws-sdk gem installed, but that's irrelevant at the moment because I can't even get the uploading to work on my local system.

I've followed all the instructions to prepare the application to handle video uploading: I've installed necessary gems, created the actual paperclip for the Video model (I named the paperclip "film"), ran the migration, and added the association to my Video model itself. I also whitelisted the :film attribute in my video controller parameters, and I have the correct field for :film in my new video form.

When I run my local server I go to my videos#new page and fill out the form, attach the file for :film, and submit the form. It takes about 10 seconds until it loads the following error:

Av::UnableToDetect in VideosController#create  Unable to detect any supported library    Extracted source (around line #10):    @video = Video.new(video_params)  

I have no idea what's going on here. When I look at other people who have had the exact same error message "Unable to detect any supported library", they always simply forgot to run the paperclip migration or something like that. I've followed all of those necessary steps.

Here is my :film related code in my Video.rb model

has_attached_file :film, styles: {      :medium => {        :geometry => "640x480",        :format => 'mp4'      },      :thumb => { :geometry => "160x120", :format => 'jpeg', :time => 10}  }, :processors => [:transcoder]  validates_attachment_content_type :film, content_type: /\Avideo\/.*\Z/  

and here's my strong parameters in my videos_controller

def video_params    params.require(:video).permit(:title, :description, :film, :preview_image,                             award_attributes: [:id, :title, :body, :award_image])  end  

And here is the database schema relevant to my video model. Preview image is a separate paperclip (its an image), which I've had for a few weeks and it works completely fine.

create_table "videos", force: :cascade do |t|      t.string   "title"      t.string   "description"      t.datetime "created_at",                 null: false      t.datetime "updated_at",                 null: false      t.string   "preview_image_file_name"      t.string   "preview_image_content_type"      t.integer  "preview_image_file_size"      t.datetime "preview_image_updated_at"      t.string   "film_file_name"      t.string   "film_content_type"      t.integer  "film_file_size"      t.datetime "film_updated_at"    end  

I also have a feeling it may have something to do with my gems, here's my gemfile:

gem 'paperclip', :git=> 'https://github.com/thoughtbot/paperclip', :ref => '523bd46c768226893f23889079a7aa9c73b57d68'  gem 'aws-sdk'  gem 'paperclip-av-transcoder'  

I've already tried it with just the plain 'paperclip' gem, with no reference to git. It still doesn't work

Thanks in advance for any help you all can give me!

Rails 4 scope has_many

Posted: 28 Apr 2016 06:49 AM PDT

I have two models

class Portfolio < ActiveRecord::Base    has_many :project_types, dependent: :destroy  end    class ProjectType < ActiveRecord::Base    belongs_to :portfolio  end  

ProjectType model has field ptype. It can be 'web' or 'mobile', etc. How can I get all 'web' or 'mobile' portfolios using scopes?

Rake extensions in non-development environment

Posted: 28 Apr 2016 06:24 AM PDT

I use Ruby 2.2.0, Rails 4.2.6 and method String#pathmap. In 1.9.3 it was a String public instance method, but since 2.0.0 it moved into rake/ext/string.rb extention.

Problem is that I can use this method in rails console and when i start my localhost all works fine, but it gives me exception in production environment. I restarted Spring, no success.

I know how to solve this problem, my question is why it works in one environment and does not work in other?

Restrict editing a resource based resource attribute

Posted: 28 Apr 2016 06:55 AM PDT

The logic of the application that I currently work on demands a Payment mustn't be editable if its status is open. I see two ways of implementing this:

1 A routing constraint like:

constraint: lambda { |req| Payment.find(req.id).status != 'open' }  

2 A simple condition in PaymentsController#edit:

if @payment.status == 'open'    redirect_to payments_path  end  

What option should I go for? Which is more suitable and clean, Rails-ish? Is there any other option? If I go with the first option and have a resources :payments, how can I add the constraint only for the edit route?

ActionView::Template::Error (undefined method `company' for #<Model:0x007f96dcdea650>)

Posted: 28 Apr 2016 06:11 AM PDT

I have an issue with rails orm when i tried to get a field from a "belongs_to" model.

Processing by OdooHrDepartementController#index as HTML    Current user: admin (id=1)    Rendered plugins/redmine_odoo_link/app/views/odoo_hr_departement/index.html.erb within layouts/base (7.6ms)  Completed 500 Internal Server Error in 140.0ms    ActionView::Template::Error (undefined method `company' for #<OdooHrDepartement:0x007f96dcdea650>):      14:   <tr>      15:   <td class="username"><%= dp.create_date %></td>      16:   <td class="firstname"><%= dp.name %></td>      17:   <td class="lastname"><%= link_to dp.company.name , { :action => "show_companies", :id => dp.company_id }%></td>      18:   <td class="email"><%= dp.note %></td>      19:   <td class="email"><%= dp.OdooHrDepartement_id %></td>      20:   <td class="email"><%= dp.OdooUsers_id %></td>    activemodel (3.2.19) lib/active_model/attribute_methods.rb:407:in `method_missing'  

This is my view:

<h2>odoo departments</h2>    <table class="list">    <thead><tr>    <th>create date</th>    <th>name</th>    <th>company_id</th>      <th>note</th>      <th>parent_id</th>      <th>manager_id</th>    </tr></thead>    <tbody>  <% for dp in @departments -%>    <tr>    <td class="username"><%= dp.create_date %></td>    <td class="firstname"><%= dp.name %></td>    <td class="lastname"><%= link_to dp.company.name , { :action => "show_companies", :id => dp.company_id }%></td>    <td class="email"><%= dp.note %></td>    <td class="email"><%= dp.OdooHrDepartement_id %></td>    <td class="email"><%= dp.OdooUsers_id %></td>    </tr>  <% end -%>    </tbody>  </table>  

This is my model:

    class OdooHrDepartement < ActiveRecord::Base      belongs_to :Company    belongs_to :OdooHrDepartement    belongs_to :OdooUsers   end  

This is my controller:

class OdooHrDepartementController < ApplicationController    unloadable        def index      @departments = OdooHrDepartement.all    end      def show_companies        @company = Company.find(params[:id])     end    end  

there are my routes:

    get 'odoo_departments', :to => 'odoo_hr_departement#index'  get 'odoo_departments/:id/' , :to => 'odoo_hr_departement#show_companies'  

finally this is my migration code :

class CreateOdooHrDepartements < ActiveRecord::Migration  

def change create_table :odoo_hr_departements do |t| t.timestamp :create_date t.string :name t.belongs_to :company, index: true t.text :note t.belongs_to :OdooHrDepartement t.belongs_to :OdooUsers end end end

Some help please ??

rails api dock syntax

Posted: 28 Apr 2016 06:06 AM PDT

ROR Api Dock always starts with a syntax of the method. My example will be link_to:

link_to(name = nil, options = nil, html_options = nil, &block) public

My question is on the "name=nil" or "something = nil" which i see on most every command.

A second example: url_for(options = nil)

Can someone explain what is the point of this or what it is trying to say..does it mean that the option is optional?

Why is it important..

net-ldap credentials error due to simple vs generic method.

Posted: 28 Apr 2016 06:05 AM PDT

I am trying to use net-ldap to query our ldap server. I can authenticate through adauth so the ldap server is responding.

I switched from activeldap to net-ldap because I couldn't get a query working with activeldap. I could not get a connection for querying with net-ldap either. I finally traced it to my ldap server apparently wanting a method of 'generic'. However, when I change the settings for net-ldap from simple to generic, I get an error.

I used the ldp.exe tool from microsoft to test my ldap connections separately from the rails app.

I have the following gems installed.

gem 'adauth'                        # for active directory/rails integration  gem 'activeldap'                    # required with adauth to provide the active directory connection  gem 'net-ldap'  

The index method in my observations controller has the following (Some info is xxx'd out)

  require 'rubygems'      require 'net/ldap'      ldap = Net::LDAP.new :host => '10.0.0.22',                           :port => 389,                           :base => "dc=xxxxx,dc=com",                           :auth => {                               :method => :simple,                               :username => 'xxxxxx',                               :bind_dn => "uid=xxxxx,ou='xxxxx',dc=xxxx,dc=com",                               :password => 'xxxxx'                           }        filter = Net::LDAP::Filter.eq( "cn", "George*" )      treebase = "dc=xxxxx,dc=com"        ldap.search( :base => treebase, :filter => filter ) do |entry|        puts "DN: #{entry.dn}"        entry.each do |attribute, values|          puts "   #{attribute}:"          values.each do |value|            puts "      --->#{value}"          end        end      end        p ldap.get_operation_result  

when I go to the index, I have ldap.get_operation_result displayed which shows

<OpenStruct extended_response=nil, code=49, error_message="80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1\u0000", matched_dn="", message="Invalid Credentials">  

52e says that the password is bad.

If I change the method to generic, I get

Net::LDAP::AuthMethodUnsupportedError in ObservationsController#index  Unsupported auth method (generic)    Rails.root: C:/Users/cmendla/RubymineProjects/employee_observations    Application Trace | Framework Trace | Full Trace  app/controllers/observations_controller.rb:61:in `index'  

If I test using ldp.exe with the same credentials I'm using above using generic, I get

res = ldap_bind_s(ld, NULL, &NtAuthIdentity, 1158); // v.3      {NtAuthIdentity: User='railsauthentication'; Pwd= <unavailable>; domain = 'ccttapes1.com'.}  Authenticated as dn:'railsauthentication'.  

If I switch to simple, I get a failure to bind of

res = ldap_simple_bind_s(ld, 'railsauthentication', <unavailable>); // v.3  Error <49>: ldap_simple_bind_s() failed: Invalid Credentials  Server error: 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1  

Apparently my ldap server is looking for the method being generic but net-ldap will not allow me to set the method to generic

'gem install ffi' failed on Mac OS X Yosemite 10.10.5

Posted: 28 Apr 2016 05:39 AM PDT

I'm trying to set up a RoR environment under RVM on Mac OS X Yosemite 10.10.5 on my macbook pro. The ruby version that I need to install is 1.9.3-p194 because it's required for my software development project.

So far, I have the following software installed on my Macbook:

RVM  ruby 1.9.3-p194  xcode v6.4 and the respective version of command line tools  Mac OS X version: 10.10.5 Yosemite  

It seems I'm running into a problem that the ffi gem (an independency of my project) cannot be built successfully.

I get the following error whenever I try to install the gem via the command "gem install ffi -v '1.9.3'"

MacBook-Pro:demo-project apple$ gem install ffi -v '1.9.3'  Building native extensions.  This could take a while...  ERROR:  Error installing ffi:      ERROR: Failed to build gem native extension.        /Users/apple/.rvm/rubies/ruby-1.9.3-p194/bin/ruby -r ./siteconf20160428-1898-idt325.rb extconf.rb  checking for ffi_call() in -lffi... *** 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      --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=/Users/apple/.rvm/rubies/ruby-1.9.3-p194/bin/ruby      --with-ffi_c-dir      --without-ffi_c-dir      --with-ffi_c-include      --without-ffi_c-include=${ffi_c-dir}/include      --with-ffi_c-lib      --without-ffi_c-lib=${ffi_c-dir}/lib      --with-libffi-config      --without-libffi-config      --with-pkg-config      --without-pkg-config      --with-ffilib      --without-ffilib  /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:381:in `try_do': The compiler failed to generate an executable file. (RuntimeError)  You have to install development tools first.      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:461:in `try_link0'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:476:in `try_link'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:619:in `try_func'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:845:in `block in have_library'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:790:in `block in checking_for'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:284:in `block (2 levels) in postpone'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:254:in `open'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:284:in `block in postpone'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:254:in `open'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:280:in `postpone'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:789:in `checking_for'      from /Users/apple/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/mkmf.rb:840:in `have_library'      from extconf.rb:20:in `<main>'    extconf failed, exit code 1    Gem files will remain installed in /Users/apple/.rvm/gems/ruby-1.9.3-p194/gems/ffi-1.9.3 for inspection.  Results logged to /Users/apple/.rvm/gems/ruby-1.9.3-p194/extensions/x86_64-darwin-14/1.9.1/ffi-1.9.3/gem_make.out  

I said I have the xcode command line tools installed, but notice from the given error below that it gave me a hint "You have to install development tools first".

Didn't I have it installed already? I was asking myself out of curiousity. Then I googled and found out the way how to check if I have xcode command line tools installed. Then I launched the terminal and issued that command as illustrated below, and the result did confirm that the piece of software was already installed.

MacBook-Pro:demo-project apple$ xcode-select -p  /Applications/Xcode.app/Contents/Developer  

Here is also my gcc version:

MacBook-Pro:demo-project apple$ gcc -v  Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1  Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)  Target: x86_64-apple-darwin14.5.0  Thread model: posix  

I have searched all over the web and tried many solutions, but, unfortunately, without success. Any advice would be very much appreciated to get this to work.

Patching complete todos in Ruby on Rails 4

Posted: 28 Apr 2016 06:17 AM PDT

I'm trying to add the ability to complete a todo item by patching in :complete method. Is it possible to use a checkbox for this rather than the link_to I have below? I would very much like a checkbox so it feels like the task is ticked off.

My View

<%= link_to "Mark as complete", complete_todo_path(todo.id), method: :patch %>  

My Controller

def complete    @todo.update_attribute(:completed_at, Time.now)    redirect_to dashboard_path, notice: "Todo item completed"  end  

My Resources

resources :todos do   member do       patch :complete   end  end  

Thanks for any help.

Rails application httpi or curb error

Posted: 28 Apr 2016 05:07 AM PDT

I have rails application on two virtual machines which communicate with other services via xml. I use httpi gem to make the communication between our servers.Today I found a strange error on the first virtual machine (the code is equal on both machines).

url::Err::ConnectionFailedError: Couldn't connect to server  from /home/ruby/apps/bo/production/shared/bundle/ruby/1.9.1/bundler/gems/httpi-40200d372806/lib/httpi/adapter/curb.rb:29:in `http_post'  

I create new objects on both machines and check for difference but the difference is only the username and passoword.

Rails : How we can configure delay_job queue with multiple database in Sub-domain model?

Posted: 28 Apr 2016 05:03 AM PDT

An example scenerio:

http://cust1.example.com and http://cust2.example.com

Now based on the subdomain cust1 and cust2, the rails application will connect to each customers own postgresql database.How delay job queue can select DB Runtime dynamically ?

Money-rails gem - how to overide default currency and show decimal points

Posted: 28 Apr 2016 05:48 AM PDT

I'm using the rails-money gem for the first time for an events app I'm building. I have an events model which has a 'price' column with type integer. I want the user to be able to type in whatever variation they want (within reason) for the cost of an event - e.g £15.99, 15.99 etc but the show output needs to look tidy and appropriate (£15.99). At the moment my input field allows me to put a decimal point on the form but it doesn't recognise this on the show page (£15.99 just shows as 15). Also, I have a currency select field with the 3 main currencies as choices £/€/$ but whatever choice I make on the show page it comes out as $ so as with the above example £15.99 shows as $15. How do I fix this?

This is the code I have at the moment -

Event.rb

 class Event < ActiveRecord::Base    belongs_to :category  belongs_to :user  has_many :bookings      has_attached_file :image, styles: { medium: "300x300>" }  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/      monetize :price, with_model_currency: :currency         end  

money.rb

    # encoding : utf-8    MoneyRails.configure do |config|      # To set the default currency    #    #config.default_currency = :gbp      # Set default bank object    #    # Example:    # config.default_bank = EuCentralBank.new      # Add exchange rates to current money bank object.    # (The conversion rate refers to one direction only)    #    # Example:    # config.add_rate "USD", "CAD", 1.24515    # config.add_rate "CAD", "USD", 0.803115      # To handle the inclusion of validations for monetized fields    # The default value is true    #    # config.include_validations = true      # Default ActiveRecord migration configuration values for columns:    #    # config.amount_column = { prefix: '',           # column name prefix    #                          postfix: '_cents',    # column name  postfix    #                          column_name: nil,     # full column name     (overrides prefix, postfix and accessor name)    #                          type: :integer,       # column type     #                          present: true,        # column will be created    #                          null: false,          # other options will be    treated as column options    #                          default: 0    #                        }    #    #config.currency_column = { prefix: '',    #                         postfix: '_currency',    #                         column_name: nil,    #                       type: :string,    #                   present: true,    #                    null: false,    #                   default: 'GBP'    #                }      # Register a custom currency    #    # Example:    # config.register_currency = {    #   :priority            => 1,    #   :iso_code            => "EU4",    #   :name                => "Euro with subunit of 4 digits",    #   :symbol              => "€",    #   :symbol_first        => true,    #   :subunit             => "Subcent",    #   :subunit_to_unit     => 10000,    #   :thousands_separator => ".",    #   :decimal_mark        => ","    # }      config.register_currency = {      "priority": 1,      "iso_code": "GBP",      "name": "British Pound",      "symbol": "£",      "alternate_symbols": [],      "subunit": "Penny",      "subunit_to_unit": 100,      "symbol_first": true,      "html_entity": "&#x00A3;",      "decimal_mark": ".",      "thousands_separator": ",",      "iso_numeric": "826",      "smallest_denomination": 1    }      config.register_currency = {      "priority": 2,      "iso_code": "USD",      "name": "United States Dollar",      "symbol": "$",      "alternate_symbols": ["US$"],      "subunit": "Cent",      "subunit_to_unit": 100,      "symbol_first": true,      "html_entity": "$",      "decimal_mark": ".",      "thousands_separator": ",",      "iso_numeric": "840",      "smallest_denomination": 1    }      config.register_currency = {      "priority": 3,      "iso_code": "EUR",      "name": "Euro",      "symbol": "€",      "alternate_symbols": [],      "subunit": "Cent",      "subunit_to_unit": 100,      "symbol_first": true,      "html_entity": "&#x20AC;",      "decimal_mark": ",",      "thousands_separator": ".",      "iso_numeric": "978",      "smallest_denomination": 1    }           # Set default money format globally.    # Default value is nil meaning "ignore this option".    # Example:    #    # config.default_format = {    #   :no_cents_if_whole => nil,    #   :symbol => nil,    #   :sign_before_symbol => nil    # }      # Set default raise_error_on_money_parsing option    # It will be raise error if assigned different currency    # The default value is false    #    # Example:    # config.raise_error_on_money_parsing = false  end  

_form.html.erb

<%= f.collection_select :category_id, Category.all, :id, :name, {prompt: "Choose a category"} %>  <!-- The above code loop assigns a category_id to each event -->    <%= f.input :image, as: :file, label: 'Image' %>  <%= f.input :title, label: 'Event Title' %>  <label>Location</label><%= f.text_field :location, id: 'geocomplete' %></br>  <label>Date</label><%= f.text_field :date, label: 'Date', id: 'datepicker' %>  <%= f.input :time, label: 'Time' %>  <%= f.input :description, label: 'Description' %>  <label>Number of spaces available</label><%= f.text_field :number_of_spaces, label: 'Number of spaces' %>  <%= f.input :is_free, label: 'Tick box if Event is free of charge' %>  <%= f.input :currency, :collection => [['£GBP - British Pounds',1],['$USD - US Dollars',2],['€EUR - Euros',3]] %>  <%= f.input :price, label: 'Cost per person (leave blank if free of charge)' %>  <%= f.input :organised_by, label: 'Organised by' %>  <%= f.input :url, label: "Link to Organiser site" %>    <%= f.button :submit, label: 'Submit' %>    <% end %>     

show.html.erb

<%= image_tag @event.image.url %>    <h1><%= @event.title %></h1>  <p>Location </p>  <p><%= @event.location %></p>  <p>Date</p>  <p><%= @event.date.strftime('%A, %d %b %Y') %></p>  <p>Time</p>  <p><%= @event.time.strftime('%l:%M %p') %></p>  <!-- above expresses date and time as per UK expectations -->  <p>More details</p>  <p><%= @event.description %></p>  <p>Number of Spaces available</p>   <p><%= @event.number_of_spaces %></p>  <% if @event.is_free? %>    <p>This is a free event</p>  <% else %>  <p>Cost per person</p>  <p><%= humanized_money_with_symbol @event.price %></p>  <% end %>  <p>Organiser</p>  <p><%= @event.organised_by %></p>  <p>Organiser Profile</p>  <button><%= link_to "Profile", user_path(@event.user) %></button>  <p>Link to Organiser site</p>  <button><%= link_to "Organiser site", @event.url %></button>    <p>Submitted by</p>   <p><%= @event.user.name %></p>      <% if user_signed_in? and current_user == @event.user %>  <%= link_to "Edit", edit_event_path %>  <%= link_to "Delete", event_path, method: :delete, data: { confirm: "Are you   sure?"} %>  <%= link_to "Back", root_path %>  <% else %>  <%= link_to "Back", root_path %>  <%= link_to "Book the Event", new_event_booking_path(@event) %>  <% end %>  

The rails-money ReadMe file states recommends that the object handling money - in this instance 'price' - can be 'monetized via migration. Is this mandatory before the gem helpers will work?

Capistrano Multiple Deploy Stages

Posted: 28 Apr 2016 04:51 AM PDT

I have a Rails app and I would like to use Capistrano to deploy two versions: production and staging.

On my deploy.rb file I have: set :stages, ['staging', 'production']

Then how can I use two paths without overriding them?

set :deploy_to, '/home/deploy/Sites/staging/myname'

set :deploy_to, '/home/deploy/Sites/production/myname'

I've seen this answer but I'd like to keep the command line clean.

Update associated 'latest' model

Posted: 28 Apr 2016 05:55 AM PDT

I have the following two models in my application, Product and Price

A Product describes the product (name, description, etc.) and thePrice has a value, first_seen_at (datetime) and last_seen_at (datetime).

A Product has_many Prices.

The idea is that when a the price of a product changes, the latest Price record is updated:

  • If the value of the new price is the same as the existing price, last_seen_at is updated
  • If the value of the new price is different to the existing price, a new Price record is created with the new details

I want to be able to access the latest price of a product, so currently use product.prices.last.value where product is any given product from the database

Is there a better way of achieving this? To add a price to the database, I'm currently performing the following actions:

  1. Find product in database
  2. Find latest price for that product
  3. Check for difference in price
  4. Either update price record or create a new price record

I know I could store the latest_price in the Product record, but the data would then be duplicated...

EmberJS - how to restructure embedded models?

Posted: 28 Apr 2016 06:27 AM PDT

Note: Using Ember Rails 0.18.2 and ember-source 1.12.1

I have inherited an Ember app that has a strange function. I am new to Ember so maybe this is normal, but I find it odd.

There are 3 models:

  1. Parents
  2. Games
  3. Comments

When a Parent views a game the url looks like this:

/<parent slug>/games/<game_id>  

(the slug is just a unique id for the parent).

At this url there is a template that has this code:

  {{#unless commentsOpen}}    {{#link-to 'comments' class="Button easyButton"}}Chat with parents in your pod{{/link-to}}    {{/unless}}      {{outlet}}  

Clicking the above button then changes the url to this:

/<parent slug>/games/<game_id>/comments  

Then all the comments appear for that game.

I need to remove that button from the view and have Comments display automatically for each Game.

The API is Rails, and I can already change the API endpoint to return all the Comments at the same time a Game is requested (as an embedded array of objects).

But what do I replace {{outlet}} with? Because my understanding is that {{outlet}} is delegating to the Comments template due to this route:

App.CommentsRoute = Ember.Route.extend    model: ->      return this.store.find('comment', {        game:   @modelFor('game').get('id')        parent: @modelFor('parent').get('slug')      }).then( (models) -> models.toArray() )  

I believe I need to remove that route and make the Comments an embedded object inside the Game model. Do I then just replace outlet with something like:

{{#each comment in Game}}    <div class="commentItem">    <div class="commentItem-author">{{comment.parent_name}}</div>    <div class="commentItem-body">{{comment.body}}</div>  </div>    {{each}}  

how to add a folder (which name has a 'dot' inside) to rails javascript or stylesheet manifest?

Posted: 28 Apr 2016 04:19 AM PDT

Trying to add 'fullpage.js' (bower component & folder name) to Rails manifest 'application.js' but fail with the 'dot'. I know it can be workaround by changing the folder name to 'fullpage' manually but it will cause problem when deploy to heroku. Is there a way to make 'require_tree' accept folder name with 'dot'?

// require_tree .  //  //= require_tree ./"fullpage.js"  

How to store data in Ruby most effectively?

Posted: 28 Apr 2016 05:08 AM PDT

I am pulling data from multiple sources in ruby, like so :

<div class="News">    <% @subject.customersAssociation.each do |customer| %>      <% customer.websitesAssociation.each do |website| %>    <% website.newsAssociation.sorted_by(field('DATE')).each do |news| %>              <ul>                <li>..Print data from |customer|... </li>                <li>..Print data from |website|... </li>                <li>..Print data from |news|... </li>            </ul>         <% end %>      <% end %>   <% end %>  

I would like to change how I am structuring this code so instead of printing the data, I store it, for iterating over, and sorting, later.

So essentially, I would like to define an object or structure where I can save the data. The problem is that I need to do this on the fly - I only have access to the code in this one particular area. I cannot create a separate class etc.

I've tried a number of solutions, such as creating objects on the fly like so :

  <% testobj = testobj.create(name: "David", occupation: "Code Artist") %>  

(and instead of "David" accessing variables in the customer/website/news Entities.)

Does anyone know of an elegant/simple possible solution here?

Creating policy for complex associations

Posted: 28 Apr 2016 04:04 AM PDT

I am building a rails app where a User can be the owner of an account by being the "admin" of the account. But an Account also has_many Userswho are the "employees of the account. I expressed this relationship in my models like this :

class Account < ActiveRecord::Base    has_many :users, through: :hotels, dependent: :destroy    belongs_to :admin, class_name: "User", foreign_key: "admin_user_id"  end    class User < ActiveRecord::Base    belongs_to :account    has_one :created_account, class_name: "Account", foreign_key: "admin_user_id", inverse_of: :admin, dependent: :destroy  end  

I have a problem with my action show in UserController. I am using Pundit gem for policies and I only want two type of users to be able to access this action : - the admin of the account and the actual user related to the profile requested

Problem is I dont know how to express that within my Pundit UserPolicy. At first I tried this

def show?    (user && (record == user)) || (user && (record.account.admin == user))  end  

The first part of the statement works : user && (record == user)) but the second part won't work because if the user is the admin of the account he won't have an account_id, it will be the account that will have an admin_user_id referring to him.

I dont see how I can express this using Pundit as I only send to the UserPolicy the User instance and not the Account instance :

def show    authorize @user  end  

Am I doing something wrong in my associations ? Should I not use Pundit for this particular occurence and set up my own policy ?

rails routing to controllers in a sub folder?

Posted: 28 Apr 2016 05:00 AM PDT

I have a requirement any url like: www.servername.com/api/foo/bar/parameters

where:

  • api is static
  • foo is the controller
  • bar is action
  • parameters are params

to map to the controllers which are in api directory

(the api directory is in controllers directory)

to achieve this I did the below code but it doesn't work. Any suggestions?

 namespace :api do     match "/api/:controller(/:action(/*params))", via: [:get, :post]   end  

Method run on error with MiniTest

Posted: 28 Apr 2016 03:49 AM PDT

How can I have a method be called on error when using Minitest with Rails, to generate some extra information about the error that just happened?

How can I access to related object by string field name in Ruby on Rails ActiveRecord?

Posted: 28 Apr 2016 04:15 AM PDT

Usually when we need to use ActiveRecord related object, we write such code:

main_object.related_object  

Where main_object is instance of MainObject class and related_object is instance of RelatedObject that connected to MainObject via related_object_id field:

class MainObject < ActiveRecord::Base       :has_one => :related_object  end    class RelatedObject < ActiveRecord::Base       :belongs_to => :main_object  end  

Count of relations might be difference and more than one. Also my task supposes custom queries where I don't know which one relation will be used.

So, I want to get related object via its name, eg:

main_object.relations['related_object']  

Is it possible in Ruby on Rails ActiveRecord?

Rails_admin undefined method `associations' for nil:NilClass

Posted: 28 Apr 2016 03:38 AM PDT

I have these models:

Class A      embeds_many :b  end    Class B     belongs_to :c  end    Class C  end  

I'm working with rails_admin and mongoid. In admin, when I try to retrieve the list of C records when I'm creating an A instance I'm getting this error:

This only happens on production envirnment not in development

NoMethodError (undefined method `associations' for nil:NilClass):        /home/pablo/.rvm/gems/ruby-2.3.0@mh-backend/bundler/gems/rails_admin-355dc80f8a20/lib/rails_admin/adapters/mongoid/abstract_object.rb:10:in `initialize'        /home/pablo/.rvm/gems/ruby-2.3.0@mh-backend/bundler/gems/rails_admin-355dc80f8a20/lib/rails_admin/adapters/mongoid.rb:24:in `new'        /home/pablo/.rvm/gems/ruby-2.3.0@mh-backend/bundler/gems/rails_admin-355dc80f8a20/lib/rails_admin/adapters/mongoid.rb:24:in `get'        /home/pablo/.rvm/gems/ruby-2.3.0@mh-backend/bundler/gems/rails_admin-355dc80f8a20/app/controllers/rails_admin/main_controller.rb:138:in `get_association_scope_from_params'  

ERR max number of clients reached - Sidekiq, Redis

Posted: 28 Apr 2016 03:48 AM PDT

I've redis server and sidekiq running on different machine's. My sidekiq queues are not executing and I see that it is due to redis connections. Currently it shows 4094 connections for 8 GB RAM.

    # Server  redis_version:2.8.19  redis_git_sha1:00000000  redis_git_dirty:0  redis_build_id:881469307e643be8  redis_mode:standalone  os:Linux 4.5.0-x86_64-linode65 x86_64  arch_bits:64  multiplexing_api:epoll  gcc_version:4.9.1  process_id:9659  run_id:60eb74bfdfa441cb34c45ec442d173aaa3fdeafc  tcp_port:6379  uptime_in_seconds:1214  uptime_in_days:0  hz:10  lru_clock:2219910  config_file:/etc/redis/redis.conf    # Clients  connected_clients:4063  client_longest_output_list:0  client_biggest_input_buf:0  blocked_clients:0    # Memory  used_memory:4459283080  used_memory_human:4.15G  used_memory_rss:4472864768  used_memory_peak:4579114992  used_memory_peak_human:4.26G  used_memory_lua:35840  mem_fragmentation_ratio:1.00  mem_allocator:jemalloc-3.6.0    # Persistence  loading:0  rdb_changes_since_last_save:43074  rdb_bgsave_in_progress:0  rdb_last_save_time:1461836488  rdb_last_bgsave_status:err  rdb_last_bgsave_time_sec:-1  rdb_current_bgsave_time_sec:-1  aof_enabled:0  aof_rewrite_in_progress:0  aof_rewrite_scheduled:0  aof_last_rewrite_time_sec:-1  aof_current_rewrite_time_sec:-1  aof_last_bgrewrite_status:ok  aof_last_write_status:ok    # Stats  total_connections_received:233500  total_commands_processed:163266  instantaneous_ops_per_sec:58  total_net_input_bytes:84478142  total_net_output_bytes:70595802  instantaneous_input_kbps:21.29  instantaneous_output_kbps:39.82  rejected_connections:871145  sync_full:0  sync_partial_ok:0  sync_partial_err:0  expired_keys:76  evicted_keys:0  keyspace_hits:50574  keyspace_misses:54646  pubsub_channels:0  pubsub_patterns:0  latest_fork_usec:1137    # Replication  role:master  connected_slaves:0  master_repl_offset:0  repl_backlog_active:0  repl_backlog_size:1048576  repl_backlog_first_byte_offset:0  repl_backlog_histlen:0    # CPU  used_cpu_sys:123.94  used_cpu_user:173.16  used_cpu_sys_children:0.00  used_cpu_user_children:0.00    # Keyspace  db0:keys=120855,expires=57,avg_ttl=19346456411  

I'm not able to figure out why my sidekiq queues are not running. They are running for couple of seconds when I restart redis.

Error from sidekiq

    2016-04-28T10:10:24.327Z 11081 TID-gslcxin2w ERROR: heartbeat: EXECABORT Transaction discarded because of previous errors.      2016-04-28T10:10:29.329Z 11081 TID-gslcxin2w ERROR: heartbeat: EXECABORT Transaction discarded because of previous errors.      2016-04-28T10:10:34.330Z 11081 TID-gslcxin2w ERROR: heartbeat: EXECABORT Transaction discarded because of previous errors.      2016-04-28T10:10:39.332Z 11081 TID-gslcxin2w ERROR: heartbeat: EXECABORT Transaction discarded because of previous errors.      2016-04-28T10:10:44.334Z 11081 TID-gslcxin2w ERROR: heartbeat: EXECABORT Transaction discarded because of previous errors.      2016-04-28T10:10:49.338Z 11081 TID-gslcxin2w ERROR: heartbeat: EXECABORT Transaction discarded because of previous errors.      2016-04-28T10:10:54.341Z 11081 TID-gslcxin2w ERROR: heartbeat: EXECABORT Transaction discarded because of previous errors.  

Error from same Sidekiq log

MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.

EDIT: Redis server Disk Size

root@localhost:~# df -h  Filesystem      Size  Used Avail Use% Mounted on  /dev/xvda       189G  2.9G  185G   2% /  none            4.0K     0  4.0K   0% /sys/fs/cgroup  devtmpfs        4.0G  4.0K  4.0G   1% /dev  none            802M  248K  802M   1% /run  none            5.0M     0  5.0M   0% /run/lock  none            4.0G     0  4.0G   0% /run/shm  none            100M     0  100M   0% /run/user  

EDIT: Sidekiq logs

2016-04-28T10:43:32.226Z 11081 TID-gslcucdsk WARN: MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.  2016-04-28T10:43:32.227Z 11081 TID-gslcucdsk WARN: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis/client.rb:110:in `call'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis.rb:1421:in `block in zadd'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis.rb:37:in `block in synchronize'  /usr/local/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis.rb:37:in `synchronize'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis.rb:1415:in `zadd'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/server/retry_jobs.rb:129:in `block in attempt_retry'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/connection_pool-2.1.0/lib/connection_pool.rb:58:in `with'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq.rb:72:in `redis'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/server/retry_jobs.rb:128:in `attempt_retry'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/server/retry_jobs.rb:83:in `rescue in call'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/server/retry_jobs.rb:74:in `call'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/chain.rb:129:in `block in invoke'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/server/logging.rb:11:in `block in call'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/logging.rb:22:in `with_context'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/server/logging.rb:7:in `call'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/chain.rb:129:in `block in invoke'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/chain.rb:132:in `call'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/middleware/chain.rb:132:in `invoke'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/processor.rb:51:in `block in process'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/processor.rb:98:in `stats'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/processor.rb:50:in `process'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/calls.rb:26:in `public_send'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/calls.rb:26:in `dispatch'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/calls.rb:122:in `dispatch'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/cell.rb:60:in `block in invoke'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/cell.rb:71:in `block in task'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/actor.rb:357:in `block in task'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/tasks.rb:57:in `block in initialize'  /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/tasks/task_fiber.rb:15:in `block in create'  2016-04-28T10:43:32.234Z 11081 TID-ot2qzd49s ERROR: Error fetching message: MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.  2016-04-28T10:43:32.234Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis/client.rb:110:in `call'  2016-04-28T10:43:32.234Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis/client.rb:192:in `block in call_with_timeout'  2016-04-28T10:43:32.235Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis/client.rb:260:in `with_socket_timeout'  2016-04-28T10:43:32.235Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis/client.rb:191:in `call_with_timeout'  2016-04-28T10:43:32.236Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis.rb:1059:in `block in _bpop'  2016-04-28T10:43:32.236Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis.rb:37:in `block in synchronize'  2016-04-28T10:43:32.236Z 11081 TID-ot2qzd49s ERROR: /usr/local/lib/ruby/2.2.0/monitor.rb:211:in `mon_synchronize'  2016-04-28T10:43:32.237Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis.rb:37:in `synchronize'  2016-04-28T10:43:32.237Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis.rb:1056:in `_bpop'  2016-04-28T10:43:32.237Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/redis-3.2.0/lib/redis.rb:1101:in `brpop'  2016-04-28T10:43:32.237Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/fetch.rb:102:in `block in retrieve_work'  2016-04-28T10:43:32.238Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/connection_pool-2.1.0/lib/connection_pool.rb:58:in `with'  2016-04-28T10:43:32.238Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq.rb:72:in `redis'  2016-04-28T10:43:32.238Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/fetch.rb:102:in `retrieve_work'  2016-04-28T10:43:32.238Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/fetch.rb:37:in `block in fetch'  2016-04-28T10:43:32.238Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/util.rb:15:in `watchdog'  2016-04-28T10:43:32.238Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/sidekiq-3.3.0/lib/sidekiq/fetch.rb:33:in `fetch'  2016-04-28T10:43:32.238Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/calls.rb:26:in `public_send'  2016-04-28T10:43:32.239Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/calls.rb:26:in `dispatch'  2016-04-28T10:43:32.239Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/calls.rb:122:in `dispatch'  2016-04-28T10:43:32.239Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/cell.rb:60:in `block in invoke'  2016-04-28T10:43:32.239Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/cell.rb:71:in `block in task'  2016-04-28T10:43:32.239Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/actor.rb:357:in `block in task'  2016-04-28T10:43:32.239Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/tasks.rb:57:in `block in initialize'  2016-04-28T10:43:32.239Z 11081 TID-ot2qzd49s ERROR: /home/deploy/apps/rsscom/shared/bundle/ruby/2.2.0/gems/celluloid-0.16.0/lib/celluloid/tasks/task_fiber.rb:15:in `block in create'  2016-04-28T10:43:36.348Z 11081 TID-gslcxin2w ERROR: heartbeat: EXECABORT Transaction discarded because of previous errors.  2016-04-28T10:43:41.350Z 11081 TID-gslcxin2w ERROR: heartbeat: EXECABORT Transaction discarded because of previous errors.  

EDIT: redis rdb permissions

-rw-rw----  1 redis redis 1650667479 Apr 28 10:42 dump.rdb  

How to use render method inside a helper or presenter in Rails

Posted: 28 Apr 2016 03:09 AM PDT

This is my helper module.

module MyHelper      def render_partial      render partial: "..."    end    end  

It's raising the error: undefined method `render' for #<.... What i should include to work?

bootstrap not binding with dynamically rendered html via erb

Posted: 28 Apr 2016 03:26 AM PDT

I am working on a Rails app with Bootstrap. In one of my views I make use of 'tabs':

<ul class="nav nav-tabs" id="myTab" role="tablist">    <li class="nav-item">      <a class="nav-link active" data-toggle="tab" href="#home" role="tab" aria-controls="home">Home</a>    </li>    <li class="nav-item">      <a class="nav-link" data-toggle="tab" href="#profile" role="tab" aria-controls="profile">Profile</a>    </li>    <li class="nav-item">      <a class="nav-link" data-toggle="tab" href="#messages" role="tab" aria-controls="messages">Messages</a>    </li>    </ul>    <div class="tab-content">    <div class="tab-pane active" id="home"       role="tabpanel">...</div>    <div class="tab-pane"        id="profile"    role="tabpanel">...</div>    <div class="tab-pane"        id="messages"   role="tabpanel">...</div>  </div>  

This works fine if its hard coded HTML. When I dynamically add an extra 'li' in "nav-tabs" item:

<% if @customer.profiles.present? %>  <% @customer.profiles.each_with_index  do |profile,index| %>    <li class="nav-item">      <a class="nav-link" data-toggle="tab" href="#profile<%=index%>" role="tab"> profile-<%=index%> </a>    </li>  <% end %>  <% end %>  

and 'div' in "tab-content" with both a unique number:

<% if @customer.profiles.present? %>      <% @customer.profiles.each  do |profile,index| %>          <div class="tab-pane" id="profile<%=index%>" role="tabpanel">            <%= render :partial => 'profiles/homes_pane' , :locals => { :profile => profile}  %>          </div>      <% end %>  <% end %>  

added in the 'href' and 'id', the tabs are not working anymore.

So it seems that Bootstrap is not binding the javascript to the dynamically generated HTML elements.

Am I doing something wrong or do I need a workaround. Any suggestions are welcome.

best regards, Martijn

Wednesday, April 27, 2016

List all Mongoid models in Rails console | Fixed issues

List all Mongoid models in Rails console | Fixed issues


List all Mongoid models in Rails console

Posted: 27 Apr 2016 06:52 AM PDT

I want to list all the models which have a respective collection in my mongodb database? I'm using mongoid gem for for MongoDB.

I would try something like this

ActiveRecord::Base.send :subclasses which works fine, but I'm not using ActiveRecord.

html.erb - How to fill last row with empty divs

Posted: 27 Apr 2016 06:55 AM PDT

I have a view in my rails app that is an image gallery. The view looks like this:

view.html.erb

  <div class="photo-row">      <% @item.item_images.each_with_index do |image, index| %>        <% if (index % 3 == 0) && (index != 0) %>          </div><div class="photo-row">        <% end %>                   <div class="photo-wrapper">          <a class="fancybox" rel="group" href="<%= image.picture.large.url %>"><img class="pending-photo" src="<%= image.picture.small.url %>" alt="" /></a>        </div>      <% end %>    </div>  

As you can see the row will fill up with three images and then create a new row. For my alignment I need the last non-full row to be filled with with 3 photo-wrapper divs. For example if an @item has 7 item_images I need there to be three rows. The first two are full and the last should have 1 with the image and 2 empty wrappers.

How can I achieve this?

Application.rb override base Ruby class

Posted: 27 Apr 2016 06:49 AM PDT

I have a RoR application that is doing the following in its application.rb

Digest::MD5 = Digest::SHA256  

This in turn ensures that everytime anyone invokes Digest::MD5 that it will instead replace the result with a Digest::SHA256. I believe this will have some unintended consequences, such as runtime issues that are hard to debug. Is there any alternative to this approach or is this sound?

How to get gcm registration token using gcm gem in ruby on rails?

Posted: 27 Apr 2016 06:32 AM PDT

I am trying to implement web push notifications in my rails app using gcm gem but i am not able to get the registration token provided by the user to store it into db for sending notification. Is there any solution to get the registration id?

rails ajax request returning not found but controller function exists

Posted: 27 Apr 2016 06:27 AM PDT

I've got some problems with an ajax function. I got an 500er error from server.

ajax function looks like this:

  $.ajax({      type: "POST",      url: "<%= url_for(:controller => "movies", :action => "test") %>",      data: {inputtag: tag }    })  

in my movies controller I've got this function

 # Fügt dem Video einen Tag hinzu   def test     @tag = Tag.new     if request.post?        @tag.update_attributes(params[:inputtag])        if @tag.save          redirect_to :back        else          redirect_to :back        end      end    end  

So I don't know Why I got this error

http://lvh.me/movies/test 500 (Internal Server Error)  

How can chaining one method onto another change the original method

Posted: 27 Apr 2016 06:33 AM PDT

The easiest way to explain this conundrum is with an example:

Say I have two Mongoid models which are related via a has_many relationship: A Blog post

class Post     include Mongoid::Document     field :body, type: String       has_many :comments  end  

and it's comments

class Comment     include Mongoid::Document     field :text, type: String       belongs_to :post  end  

Now I create a Post which has two comments in IRB, and I attempt to load them via the relationship. I have some DB logging enabled so I can see when the query is made:

post.comments #=>   2016-04-27 13:51:52.144 [DEBUG MONGODB | localhost:27017 | test.find | STARTED | {"find"=>"comments", "filter"=>{"post_id"=>BSON::ObjectId('571f315e5a4e491a6be39e02')}}]   2016-04-27 13:51:52.150 [DEBUG MONGODB | localhost:27017 | test.find | SUCCEEDED | 0.000492643s]   => [#<Comment _id: 571f315e5a4e491a6be39e03, text: 'great post' >, #<Comment _id: 571f315e5a4e491a6be39e12, text: 'this!' >]  

So the comments are loaded from the DB and returned as a Mongoid::Relations::Targets::Enumerable class, which looks like an array, and it contains the two comments.

Now when I open a fresh IRB console, and take a look at the criteria used to load these comments using the criteria attribute of the Mongoid::Relations::Targets::Enumerable class instance post.comments, I get this output:

post.comments.criteria #=>   => #<Mongoid::Criteria   selector: {"post_id"=>BSON::ObjectId('571f315e5a4e491a6be39e02')}   options:  {}   class:    Comment   embedded: false>  

How come no DB requests is made in this example? It's not a caching problem as I opened a new IRB console.

How can chaining criteria onto post.comments change what the .comments method does? I took a look through Mongoid's implementation of the Mongoid::Relations::Targets::Enumerable class (source on Github), but couldn't find any clues to how it works.

Rails: Searchform for Tags

Posted: 27 Apr 2016 06:47 AM PDT

I build a simple tagging system into my webapp (I've followed these steps: http://www.sitepoint.com/tagging-scratch-rails/)

So, now it's working fine that people can click on a Tag e.g. Dogs and they are going to "app.com/search/dogs".

But, now the people should also search for tags by using a form input field. At the moment I've tried this:

<%= form_tag('search', method: 'get', controller: 'static', action: 'home') do %>    <%= text_field_tag :tag, params[:tag], placeholder: "Search Posts" %>    <%= submit_tag("Search") %>  <% end %>  

That brings the user to: "app.com/search/?utf8=✓&tag=Dogs&commit=Search" and that's not working. Is there a way to achieve the other logic?

Here some (maybe) interesting code samples:

routes.rb

# search by tags  get 'search/:tag', to: 'static#home', as: "search"  

post.rb

def self.tagged_with(name)  Tag.find_by_name!(name).posts  end  

static_controller.rb

def home    if params[:tag]      @posts = Post.tagged_with(params[:tag])    else      @posts = Post.all    end  end  

posts_helper.rb

def tag_links(tags)    tags.split(",").map{|tag| link_to tag.strip, search_path(tag.strip) }.join(" ")  end  

Sorry, I'm a real beginner :) Thank you in advance!

How to lint factories immediately with guard and factory girl?

Posted: 27 Apr 2016 06:07 AM PDT

What do I need tu put in my Guardfile (in a Rails application with RSpec and FactoryGirl) to lint all my factories every time I change a factory?

I know that it is possible to run all models spec, accordingly to this question: Using guard-rspec with factory-girl-rails, but I want to only lint them all.

I tried to do this in Guardfile, but it was not enough:

watch(%r{^spec/factories/(.+)\.rb$}) {    FactoryGirl.lint  }  

Thanks in advance.

Aptana 3 - Rails debugger not doing anything

Posted: 27 Apr 2016 06:10 AM PDT

When invoking "Debug Server" nothing happens at all, no error messages, nothing. Also, nothing happens when opening a page in the browser that has breakpoints set in it.

In case i invoke "Debug as Ruby Application" i get the following exception:

Fast Debugger (ruby-debug-ide 0.6.1.beta2, debase 0.2.1, file filtering is supported) listens on 127.0.0.1:57291  Uncaught exception: uninitialized constant ApplicationController      /home/jobmob/dev/jm10/app/controllers/sessions_controller.rb:1:in `<top (required)>'      /home/jobmob/.rbenv/versions/2.3.0/bin/rdebug-ide:23:in `load'      /home/jobmob/.rbenv/versions/2.3.0/bin/rdebug-ide:23:in `<main>'  

But i think this is not the right way to debug a Rails appliation anyways, is it?

Here is my configuration:

  • Aptana Studio 3.6.1 on CentOS 7
  • Ruby 2.3.0
  • Rails 4.2.6
  • ruby-debug-ide 0.6.1 beta2

Phoenix/Elixir vs Rails - full stack benchmark? [on hold]

Posted: 27 Apr 2016 06:32 AM PDT

I'm new to Elixir/Phoenix and looking for full stack benchmarks comparisons with Rails.

I found this post (but it doesn't hit the database) http://www.littlelines.com/blog/2014/07/08/elixir-vs-ruby-showdown-phoenix-vs-rails/

A Blog index page would be fine (with variable posts list) - as long as it hits the database.

Thanks for any input!

Stop rails url_helper from requesting a lot of unnecessary objects from database

Posted: 27 Apr 2016 05:52 AM PDT

I'm creating a large xml output using rails and there are a lot of urls generated by rails. There are so called items and enclosures. Every item may have one enclosure. So I'm using has_one and belongs_to relation in my model.

I'm using

enclosure_url(item.enclosure, format: :json)  

for generating the url.

What I expect: Rails should generate the url based on the id which is stored in the items table.

What now happens is, that rails is fetching each single enclosure from the database which is slowing down my system.

Enclosure Load (2.6ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11107]]  Enclosure Load (3.1ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11108]]  Enclosure Load (0.7ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11109]]  Enclosure Load (1.5ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11110]]  Enclosure Load (6.8ms)  SELECT  "enclosures".* FROM "enclosures" WHERE "enclosures"."id" = ? LIMIT 1  [["id", 11111]]  

Is there any trick stopping rails doing this or do I have to generate my url myself?

You cannot use a Stripe token more than once

Posted: 27 Apr 2016 06:24 AM PDT

I cannot seem to charge a card then create a customer on the fly in Rails 4.

def charge   token = params[:stripeToken] # can only be used once.   begin    charge = Stripe::Charge.create(      :amount => 5000,      :currency => "gbp",      :source => token,      :description => "Example charge"    )   rescue Stripe::CardError => e    # The card has been declined   end     if current_user.stripeid == nil    customer = Stripe::Customer.create(card: token, ...)    current_user.stripeid = customer.id    current_user.save   end  end  

I have looked at this but there is no such thing as token.id as token is just a String.

Rails mailer view template pass value send by a form

Posted: 27 Apr 2016 06:34 AM PDT

Its my first attempt to use the rails mailer to send email. I however is able to send plain emails but when I tried to pass the logged in user (current_user) name and params values send by the form I am getting the error. Undefined method 'params'.

payment_mailer.rb

class PaymentMailer < ApplicationMailer      def success(user)          mail(to: "#{user.first_name} #{user.last_name} <#{user.email}>", subject: "Payment Successful")      end  end  

success.html.erb

<div class = "col-sm-12">            <h1>Payment Successful</h1>            <p>Dear <%= user.first_name %>, Thank you for being a part of our system<br>              Your invoice (#<%= params[:id] %>) has been generated.            </p>          </div>          <div class = "clearfix"></div>          <div class = "col-sm-6">            <table class = "table">              <thead>                <tr>                  <th>Paid Ammount</th>                  <th>Card Transaction Fee (2.9% + 0.30)</th>                  <th>Credited Ammount</th>                </tr>              </thead>              <tbody>                <tr>                  <td>&euro;<%= params[:amount] %></td>                  <td></td>                  <td></td>                </tr>              </tbody>              <h3>Total credited amount in your Account is: </h3>            </table>          </div>          <div class = "clearfix"></div>        </div>  

payment_controller.rb

amount = params[:amount]  @user = current_user  netamt =  (amount.to_f - ((amount.to_f*2.9)/100 + 0.30))  payment = @user.payments.create(:amount => netamt, :method => "Card", :txn_code => params[:stripeToken])  @user.update_attribute(:balance, @user.balance+netamt)  PaymentMailer.success(current_user).deliver_now  

Please guide me.

Has many through doesn't persist

Posted: 27 Apr 2016 05:27 AM PDT

I have a question about the Has Many Through relationship.

I have 3 models : Artist, Skill, and Mastery

skill.rb

class Skill < ActiveRecord::Base    has_many :masteries    has_many :artists, through: :masteries  end  

mastery.rb

class Mastery < ActiveRecord::Base    belongs_to :artist    belongs_to :skill  end  

artist.rb

class Artist < ActiveRecord::Base    has_many :masteries    has_many :skills, through: :masteries  end  

Everytime I try to attach a skill to an Artist, using artist.skills << skill, a mastery is created, but the artist_id is nil. Same thing the other way around. skill.artists << artist gives me a Mastery with a nil skill_id.

Does this mean that I have to execute both every time ? Or did I miss something ?

How TO Get the email when we seleted the person name

Posted: 27 Apr 2016 05:42 AM PDT

I need an employee email-id when I'm selecting his name, if his email id is exist in database. Can any one suggest me how to do, since I have 1400 employees and their mail id, I'm getting their names in dropdown but when I'm selecting their names I need their mail id to display in the particular field......

$("#user_employee_id").change(function(){           $.ajax({                type: "GET",                url: "/User/emailcheck",                data: { email: user.email }                  });            });    user_controller.rb  def emailcheck      @user = User.search(params[:email])    end    user.rb  def self.search(email)          if email              where('email = ?',email).first          end    end  

Can any one tell how to get the email id when I click on the employee name? I need to get email id of that employee by default in email tab.

Error while installing jwt gem in CentOS

Posted: 27 Apr 2016 05:13 AM PDT

I get the following error while trying to install jwt -

gem install jwt -v '1.5.4' ERROR: Error installing jwt: invalid gem: package metadata is missing in /home/user/.rvm/gems/ruby-2.1.6/cache/jwt-1.5.4.gem

As given in the link here, I installed postgresql, but can't locate postgre in /usr

How do I solve this error?

Amazon ruby sdk on creating an EMR cluster?

Posted: 27 Apr 2016 05:04 AM PDT

I have setup the aws sdk ruby on rails gem and i make a successful authentication. But i cannot seem to find any tutorials on creating an EMR cluster programmatically using the SDK. any tutorials you know of?

i am testing things out below

class HomeController < ApplicationController      def index      emr = Aws::EMR::Client.new      p emr.operation_names    end    end  

seem to get successfully the operations.

Writing to .zip file from binary data

Posted: 27 Apr 2016 06:48 AM PDT

I am trying to write a rails test (Using Capybara & Poltergeist) to test .zip file download functionality.

I have the binary data of a .zip file being returned from an XHR request and I am hoping to write this data into a .zip file locally and carry out further tests from there.
The following method emulates a click on a button which, when in-app, returns a zip file of all the files that have been selected:

# Perform XHR  def download_file(link)    page.execute_script("window.downloadFile = function(){ var url = window.location.protocol + '//' + window.location.host + '#{link}'; return getFile(url); }")    page.execute_script("window.getFile = function(url){ var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.responseType = 'blob'; xhr.send(); return xhr.response; }")      begin      file = page.evaluate_script('downloadFile()')    rescue      raise "Error during XHR. Is url valid?"    end    file  end  

I am trying to write the response to file here:

file = download_file(url)  file_path = "#{Rails.root}/tmp/files/download.zip"  File.open(file_path, 'wb'){ |f| f.write file }  

When trying to unzip the resulting file using unzip tmp/files/download.zip I'm given the following response:

Archive:  tmp/files/download.zip    caution:  zipfile comment truncated  error [tmp/files/download.zip]:  missing 3182550208 bytes in zipfile    (attempting to process anyway)  error [tmp/files/download.zip]:  start of central directory not found;    zipfile corrupt.    (please check that you have transferred or created the zipfile in the    appropriate BINARY mode and that you have compiled UnZip properly)  

I have tried overriding the MIME type to text/plain, application/zip etc. but to no avail.
Any suggestions?

How to save multiple dates in ruby

Posted: 27 Apr 2016 05:04 AM PDT

i have 2 models property and property dates. i need to save multiple start date and end date for a property in property dates tables table fields(property_id,start_date_end_date) my model tables

`class Property < ActiveRecord::Base      has_many :property_dates      accepts_nested_attributes_for :property_dates  end`

`class PropertyDate < ActiveRecord::Base  	belongs_to :property  end`
my controller

class Users::PropertiesController < ApplicationController    before_filter :authenticate_user!    before_action :set_properties, only: [:show, :edit, :update, :destroy]        def index      @properties =  Property.where(:user_id=>current_user.id)    end      def list      @properties = Property.all    end      def show      end         def new     @property= Property.new    end          def edit    end      def create      @property = Property.new(properties_params)      respond_to do |format|        if @property.save   format.json { render :index, status: :created, location: @property }        else          format.html { render :new }          format.json { render json: @property.errors, status: :unprocessable_entity }        end      end    end         def update      respond_to do |format|        if @property.update(properties_params)          format.json { render :back, status: :ok, location: @property }        else          format.json { render json: @property.errors, status: :unprocessable_entity }        end      end    end         def destroy      @property.destroy      respond_to do |format|        format.html { redirect_to  :back, notice: 'Property was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_properties        @property = Property.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def properties_params        params.require(:property).permit(:Space_name,:user_id,:address,:pincode,:image,property_dates_attributes: [ :start_date, :end_date ])

form property form i need to select multiple dates and need to save to property_dates table

my form.html.erb

 `<%= simple_nested_form_for ([:users,@property])  do |f| %>    <%= f.fields_for :property_dates do |p| %>      <%= p.text_field :start_date%>      <%= p.text_field :end_date%>    <% end %>    <% end %>`

When i write form it is not visible in my form. Why it is happening like that? Any error in my code. Please help.

Ruby on rails. Add facebook.com/ to URL if not present

Posted: 27 Apr 2016 05:29 AM PDT

my users have the option to add their website, facebook and twitter URL's to their profile.

I want to let them enter either the full URL (http://www.facebook.com/USERNAME) or part of the URL Eg. www.facebook.com/USERNAME or just USERNAME, and then have the https://facebook.com/ added automatically if needed. I want the http:// as then the entered URL will link directly to their website/facebook etc.

For the website URL I have:

before_validation :add_url_protocol    def add_url_protocol    if self.website && !url_protocol_present?      self.website = "http://#{self.website}"    end  end    def url_protocol_present?    self.website[/\Ahttp:\/\//] || self.website[/\Ahttps:\/\//]  end  

There is then further regex validation. This works fine.

The thing is I don't have much of an idea about regex and I am unsure on how to add the facebook.com/ part to this before_validation code.

Any help would be greatly appreciated, thanks.

UPDATE:

def add_url_protocol    if self.website && !url_protocol_present?      self.website = "http://#{self.website}"    end    if self.facebook && !url_facebook_present?      self.facebook = "http://facebook.com/#{self.facebook}"    end  end  

This almost works. If a user inputs USERNAME then the output is good. If the user inputs www.facebook.com/USERNAME then the ouput becomes http://facebook.com/www.facebook.com/USERNAME

Let users join multiple leagues (groups) and switch between them

Posted: 27 Apr 2016 05:13 AM PDT

I'm creating an application to store played FIFA Games and build a private leaderboard with friends.

I managed to add a user to a league (private group) but now I want to let users join multiple leagues and easily switch between them.

I've added a league_id to games and to users.

When loading the leaderboard I'm only showing the users that match current_user.league_id and for the wins and losses I'm only counting the games with that match current_user.league_id.

This works perfectly, however a user should be able to join annother league and switch easily between them. I was thinking creating another field to users that stores a collection of all joined leagues and add an action to change the active_league_id.

Can someone point me in the right direction here?

class User < ActiveRecord::Base        devise :registerable, :confirmable      devise :omniauthable, :omniauth_providers => [:facebook]        #RELATIONS SINGLE GAMES        has_many :home_games,    class_name: 'Game', foreign_key: 'home_team_user_id'      has_many :away_games, class_name: 'Game', foreign_key: 'away_team_user_id'        #RELATIONS MULTI GAMES        has_many :first_home_games,    class_name: "Multiplayergame", foreign_key: "home_team_first_user_id"      has_many :second_home_games,    class_name: "Multiplayergamer", foreign_key: "home_team_second_user_id"        has_many :first_away_games, class_name: "Multiplayergame", foreign_key: "away_team_first_user_id"      has_many :second_away_games, class_name: "Multiplayergame", foreign_key: "away_team_second_user_id"        #RELATIES SCORE CLASSEREN SINGLE GAMES         has_many :wins, class_name: 'Game', foreign_key: 'winner_id'      has_many :losses, class_name: 'Game', foreign_key: 'loser_id'        has_many :bonusses, class_name: 'Game', foreign_key: 'bonus_id'      has_many :loserbonusses, class_name: 'Game', foreign_key: 'bonus_loser_id'        has_many :firstdraws, class_name: 'Game', foreign_key: 'first_draw_id'      has_many :seconddraws, class_name: 'Game', foreign_key: 'second_draw_id'          #RELATIES SCORE CLASSEREN MULTI GAMES         has_many :firstwins, class_name: 'Multiplayergame', foreign_key: 'winner_first_id'      has_many :secondwins, class_name: 'Multiplayergame', foreign_key: 'winner_second_id'      has_many :firstlosses, class_name: 'Multiplayergame', foreign_key: 'loser_first_id'      has_many :secondlosses, class_name: 'Multiplayergame', foreign_key: 'loser_second_id'        has_many :firstbonusses, class_name: 'Multiplayergame', foreign_key: 'bonus_first_id'      has_many :secondbonusses, class_name: 'Multiplayergame', foreign_key: 'bonus_second_id'      has_many :firstloserbonusses, class_name: 'Multiplayergame', foreign_key: 'bonus_first_loser_id'      has_many :secondloserbonusses, class_name: 'Multiplayergame', foreign_key: 'bonus_second_loser_id'        has_many :firstmultidraws, class_name: 'Multiplayergame', foreign_key: 'first_multidraw_id'      has_many :secondmultidraws, class_name: 'Multiplayergame', foreign_key: 'second_multidraw_id'      has_many :thirdmultidraws, class_name: 'Multiplayergame', foreign_key: 'third_multidraw_id'      has_many :fourthmultidraws, class_name: 'Multiplayergame', foreign_key: 'fourth_multidraw_id'        belongs_to :league        has_one :league_admin, class_name: 'League', foreign_key: 'league_admin_id'    ##############################################################################################        ### TOTAL WINS CURRENT LEAGUE SINGLE PLAYER        def current_league_wins          wins.where(:league_id => self.league_id).count      end        #### TOTAL LOSSES CURRENT LEAGUE SINGLE PLAYER        def current_league_losses          losses.where(:league_id => self.league_id).count      end        #### TOTAL DRAWS CURRENT LEAGUE SINGLE PLAYER        def draws          firstdraws.where(:league_id => self.league_id).count + seconddraws.where(:league_id => self.league_id).count      end    #####################################################################################################          #### TOTAL WINS CURRENT LEAGUE MULTIPLAYER        def current_league_multi_wins          firstwins.where(:league_id => self.league_id).count + secondwins.where(:league_id => self.league_id).count      end          #### TOTAL LOSSES CURRENT LEAGUE MULTIPLAYER        def current_league_multi_losses          firstlosses.where(:league_id => self.league_id).count + secondlosses.where(:league_id => self.league_id).count      end        #### TOTAL DRAWS CURRENT LEAGUE MULTIPLAYER        def multidraws      firstmultidraws.where(:league_id => self.league_id).count + secondmultidraws.where(:league_id => self.league_id).count + thirdmultidraws.where(:league_id => self.league_id).count + fourthmultidraws.where(:league_id => self.league_id).count        end  

Controller scoreboard:

class ScoreboardController < ApplicationController      before_action :authenticate_user!        #LAAD ALLE USERS GERANSCHIKT VOLGENS SCORE        def index          @users = User.where(:league_id => current_user.league_id).sort_by(&:score).reverse            end    end  

What I need to achieve is that users can easily switch between the joined leagues and that if a user changes leagues he still appears in all the leaderboards. If a user changes league now he's not in that leaderboard any more until he rejoines, wich is normal since his league_id changes.

Rails printing array to selection_tag

Posted: 27 Apr 2016 05:22 AM PDT

I want to print an array to selection_tag

tried it this way:

 <%= f.select(:currency, {"€","$"} { |p| [p[0], p[1]] }, {}, {:class => "form-control"}) %>  

But got an synthax error...

What's my failure?

Thanks

Pundit, the record has no my model attributes

Posted: 27 Apr 2016 04:58 AM PDT

i have a model CustomerProfile, with a column i24wholesaleid In my Pundit policy CustomerProfilePolicy. i wanted to add some authorization logic to the show method so:

 def show?        if ((user.wholesale? and record.i24wholesaleid == user.customer_profile_id)) ...  

but i receive a NoMethodError:

undefined method `i24wholesaleid' for #<Class:0x007f30ce23d600>  

and i don't understand why record is a generic class, it should be an instance of my model class, isn't it? The policy is just extending the default ApplicationPolicy created by Pundit.

thanks.

Rails Omniauth - multiple social logins for same user

Posted: 27 Apr 2016 04:11 AM PDT

I've set up my Rails app to incorporate both Facebook and Twitter sign-in options and both work fine. However, when logging in for first time they create a new user rather than log in as the same user. How do I set up my app so one user can have multiple log in options - facebook, twitter or AN Other? Do I simply need to set up a seperate Authorizations/Authentications model and create an association? What other code is required?

Here's my code so far -

OmniauthCallbacks Controller -

class OmniauthCallbacksController < Devise::OmniauthCallbacksController    def all        user = User.from_omniauth(request.env["omniauth.auth"])      if user.persisted?          flash.notice = "Signed in!"          sign_in_and_redirect user       else          session["devise.user_attributes"] = user.attributes           redirect_to new_user_registration_url      end      end      alias_method :twitter, :all   alias_method :facebook, :all              end  

User model -

class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable, :omniauthable,     omniauth_providers: [:twitter, :facebook]         has_many :events       has_many :bookings        def self.from_omniauth(auth)      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|          user.provider = auth.provider          user.uid = auth.uid          user.username = auth.info.nickname      end  end    def self.new_with_session(params, session)      if session["devise.user_attributes"]          new(session["devise.user_attributes"], without_protection: true) do |user|              user.attributes = params              user.valid?          end      else          super      end  end    def password_required?      super && provider.blank?  end    def update_with_password(params, *options)      if encrypted_password.blank?          update_attributes(params, *options)      else          super      end  end       end  

Jquery not working in Production & Heroku but works perfectly well in development

Posted: 27 Apr 2016 04:06 AM PDT

your advise would be much appreciated.

Heroku and my production environment are not picking up my jQuery coding (Javascript files) - i have literally tried every code, suggestions and command and still unsuccessful. i have pasted my files below - if one could point out what it is i am doing wrong that needs to be corrected would much appreciate it.

-

views/layout/application.html.erb

<!DOCTYPE html>  <html lang="en">    <head>      <meta charset="utf-8" />      <meta name="viewport" content="width=device-width, initial-scale=1.0" />        <title><%= full_title(yield(:title)) %></title>        <%= stylesheet_link_tag    "application" %>      <%= javascript_include_tag "vendor/modernizr" %>        <%= csrf_meta_tags %>      <%= favicon_link_tag 'img-logo-five.png' %>      <%= favicon_link_tag 'apple-touch-icon-#{196}x#{196}.png', rel: 'apple-touch-icon', type:'image/png' %>    </head>      <body data-no-turbolink="true">      <div class="medium-12 columns container">           <% if notice %>          <div id="notice_wrapper">            <p id="notice"><%= notice %></p>          </div>        <% elsif alert %>          <div id="alert_wrapper">            <p id="alert"><%= alert %></p>           </div>        <% end %>          <%= yield %>      </div>        <%= javascript_include_tag "application" %>    </body>  </html>  

Gemfile

source 'https://rubygems.org'    gem 'rails', '4.1.10'  gem 'bcrypt', '3.1.7'  gem 'sass-rails', '~> 4.0.3'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.0.0'  gem 'jquery-rails'  gem 'turbolinks'  gem 'jbuilder', '~> 2.0'  gem 'sdoc', '~> 0.4.0',          group: :doc  gem 'foundation-rails', '5.3.1.0'  gem 'simple_form'  gem "font-awesome-rails"  gem 'devise'  gem "ransack", github: "activerecord-hackery/ransack", branch: "rails-4.1"  gem "polyamorous", :github => "activerecord-hackery/polyamorous"  gem 'carrierwave'  gem 'rmagick'  gem 'acts_as_commentable'  gem "cocoon"  gem 'geocoder'  gem 'social-share-button'  gem 'twilio-ruby'  gem 'cancancan', '~> 1.10'  gem 'public_activity'  gem 'foundation-datetimepicker-rails'  gem 'jquery-ui-rails'    group :development, :test do    gem 'sqlite3',     '1.3.9'    gem 'byebug',      '3.4.0'    gem 'web-console', '2.0.0.beta3'    gem 'spring',      '1.1.3'    gem 'quiet_assets'    gem 'mailcatcher'    gem "better_errors"    gem 'awesome_print'    gem 'pry'    gem 'binding_of_caller'  end    group :test do    gem 'minitest-reporters', '1.0.5'    gem 'mini_backtrace',     '0.1.3'    gem 'guard-minitest',     '2.3.1'  end    group :production do    gem 'pg',             '0.17.1'    gem 'rails_12factor'    gem 'unicorn',        '4.8.3'  end  

config/environments/production.rb

Rails.application.configure do    config.cache_classes = true    config.eager_load = true    config.consider_all_requests_local       = false    config.action_controller.perform_caching = true    config.serve_static_files = true    config.assets.compress = true    config.assets.js_compressor = :uglifier    config.assets.compile = true    config.assets.precompile =  ['*.js', '*.css', '*.css.erb']    config.assets.digest = true    config.log_level = :info    config.i18n.fallbacks = true    config.active_support.deprecation = :notify    config.log_formatter = ::Logger::Formatter.new    config.active_record.dump_schema_after_migration = false    config.action_mailer.default_url_options = { host: 'website.herokuapp.com' }    Rails.application.routes.default_url_options[:host] = 'website.herokuapp.com'  end  

config/locales/application.rb

require File.expand_path('../boot', __FILE__)    require 'rails/all'  Bundler.require(*Rails.groups)    module RecruitmentAfricaApp    class Application < Rails::Application      config.assets.precompile += %w(*.js)      config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]      config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]      config.action_mailer.delivery_method = :smtp      config.action_mailer.smtp_settings = {         address: "smtp.mandrillapp.com", #if using a another domain this will be provided by the domain company         port: 111,         enable_starttls_auto: true,         user_name: "email@gmail.com", #this would need to be for example info@recruitmentafrica.com         password: "#####",         authentication: :login,         domain: "gmail.com",       }    end  end  

assets/javascripts/application.js

    //= require jquery  //= require jquery_ujs  //= require foundation  //= require turbolinks  //= require jquery-ui  //= require cocoon  //= require social-share-button  //= require foundation-datetimepicker  //= require_tree .      /*=========================================      general js content    =========================================*/    $(function(){ $(document).foundation(); });      // sigin-in alert message | devise signin/signout error messages  $(document).ready(function(){    setTimeout(function(){      $('#notice_wrapper').fadeOut("slow", function() {        $(this).remove();      })    }, 2500);  });    // sigin-out alert message | devise signin/signout error messages  $(document).ready(function(){    setTimeout(function(){      $('#alert_wrapper').fadeOut("slow", function() {        $(this).remove();      })    }, 2500);  });    // jquery-ui datepicker   $(document).ready(function() {    $('.datepicker').datepicker({ dateFormat: 'MM dd, yy' });     // $('.datepicker').datepicker({ dateFormat: 'D, dd M yy' });   });  

assets/stylesheets/application.css

/*   * This is a manifest file that'll be compiled into application.css, which will include all the files   *= require_tree .   *= require_self   *= require foundation_and_overrides   *= require foundation   *= require social-share-button   *= require jquery-ui   *= require font-awesome   */  

commands & codes i have tried but still no success

  • [1.] i have re-arranged my js files in application.js
  • [2.] i have set in production.rb: config.assets.compile = true
  • [3.] i have run the command: rake assets:precompile then git push heroku master
  • [4.] i have run the command: RAILS_ENV=production bundle exec rake assets:precompile
  • [5.] i have run the command: heroku run rake assets:precompile --app appName
  • [6.] my javascript does not return a 404 HTTP error online
  • [7.] i've tried adding the gem in the gemfile gem 'jquery-turbolinks' & in application.js //= require jquery.turbolinks
  • [8.] in application.rb i've added: config.assets.precompile += %w(*.js)
  • [9.] in production.rb i have added config.assets.precompile = ['*.js', '*.css', '*.css.erb']
  • [10.] i placed in a simple alert code alert('some-unique-string') pushed to heroku but do not see the alert in the console
  • [11.] i have set: assets.compress=true
  • [12.] i have set: config.assets.compress = true & run the command RAILS_ENV=production bundle exec rake assets:precompile
  • [14.] i installed the jquery.migrate.plugin i am unsure what more to do & your help would be much appreciated. Many thanks

Rails: callback in controller to change attribute from true to false in database

Posted: 27 Apr 2016 06:22 AM PDT

so I'm testing how to make a multiplayer Tic Tac Toe game, and for this I made a User model and a Game model, and by a has_many_through association they have various game_users.

Each game has an attribute: "seeking_players", that by default is true. When I create a new game_user, I check if they're exists a game with the seeking_players attribute set to true. If such a game exists, I make a new game_user for this game and I want to set this attribute to false.

But whatever I try, I can't seem to change this attribute. So, my question: what's wrong with this code: EDIT: this is the new code after suggestions from @Малъ Скрылевъ

class GamesController < ApplicationController    before_action :logged_in_user    before_action :assign_game, only: [:new]    after_action :update_seeking_players, only: [:assign_game]      def new      @game = assign_game      @game.game_users.create(user: current_user)        redirect_to game_url(id: @game.id)    end      def game    end      private      def assign_game      @game = Game.find_by_seeking_players(true) || Game.create    end      def update_seeking_players      if @game.game_users.size == 2          @game.update(seeking_players: false)      end    end    end  

PS: I also tried changing this "seeking players" attribute in the Game model (with a callback "after_add"), which is maybe a more appropriate place? But I really can't figure out how to do this...

UPDATE:

these are the Game & GameUser model

class Game < ActiveRecord::Base      has_many :game_users      has_many :users, :through => :game_users    end    class GameUser < ActiveRecord::Base      belongs_to :game      belongs_to :user      validates :game_id, presence: true      validates :user_id, presence: true    end  

UPDATE 2 the migration for seeking_players

class AddSeekingPlayersWithIndexToGames < ActiveRecord::Migration    def change      add_column :games, :seeking_players, :boolean, :default => true      add_index :games, :seeking_players    end  end  

Getting OAuthException 191

Posted: 27 Apr 2016 04:31 AM PDT

I am getting this error when logging through Facebook on a Ruby on Rails app.

What I want is when login is OK, redirect to https://hacker-news-alexvilarrubla.c9users.io/submissions but I don't exactly know how to do this.

The routes.rb code http://pastebin.com/WFgwuVNX

The omniauth.rb http://pastebin.com/QUMdLt1h

The application.html.erb http://pastebin.com/vWBJdJAQ

User.rb http://pastebin.com/Tn5wiBvv

SessionsController http://pastebin.com/Ca2PmVkv

ApplicationController http://pastebin.com/qZ6i6WGT

I guess it is something related with the Facebook App Config.

Any help will be helpful.

Thanks, Alex.

Can I use oracle_enhanced adapter in vanity gem for AB Testing?

Posted: 27 Apr 2016 03:34 AM PDT

For my production database, I am using oracle_enhanced adapter. Is this supported by vanity gem? From https://github.com/assaf/vanity, it says: "Vanity supports multiple SQL stores (like MySQL, MariaDB, Postgres, Sqlite, etc.) using ActiveRecord, which is built into Rails". I am not sure if this etc includes Oracle.

I tried using the below in my config/vanity.yml:

production:    adapter: oracle_enhanced    host: mydb.XXX.com    username: XXX    password: XXX    port: XXXX    database: mydb  

But what I get is the error message below:

Could not find oracle_enhanced in your load path (RuntimeError)  

My config/database.yml is actually using adapter: oracle_enhanced.

Any advice what I'm missing?

Is there a way do export a database in a rails app to excel

Posted: 27 Apr 2016 04:56 AM PDT

I'm being faced with a task of having a button on my rails application which basically exports the entire sqlite database to an excel file. So that the client can make pretty little graphs and do excel like things with the information.

I have done a cheeky google search trying to find a gem but I have literally 0 clue how they work and if they actually do what I want them to do.

I have tried using the Axlsx gem, but it didn't work.

I know I'm probably going to get a lot of hate on here because its not your orthodox question, but I'm at wits end with this database.

Any ideas?

Cheers

Can I allow certain views only to be rendered in iframes?

Posted: 27 Apr 2016 04:49 AM PDT

I got an application that serves widgets inside iframes of other websites. So far so good but how can I allow these widgets views only to be loaded inside an iframe and not directly?

This should work

<iframe src="http://www.example.com/widgets/example">  

But typing in http://www.example.com/widgets/example directly into a browser shouldn't be allowed.

What is or is there a best way to achieve this in rails?