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

No comments:

Post a Comment