Tuesday, September 20, 2016

Delete a record from connection table when meets a condition | Fixed issues

Delete a record from connection table when meets a condition | Fixed issues


Delete a record from connection table when meets a condition

Posted: 20 Sep 2016 07:40 AM PDT

I have a Customer model and an Order model. A customer can have multuple orders, and the table to connect between them is customers_orders so:

Customer >> has_many: orders, :class_name => "CustomerOrders"  

Until today, I wrote

customer.orders.clear  

in order to delete all orders. It also deleted the records from the connection table.

I added a column to that connection table, lets call it blah. I want to delete the records from the connection table when the blah column has a certain value, so I tried:

customer.orders.where("blah = 3").clear  

But it does not work.

Why? And how can I handle that?

User.find_by(["name LIKE ?" not working on heroku but working on development server

Posted: 20 Sep 2016 07:35 AM PDT

What would cause this to work in development, but not production?

I have User.find_by(["name LIKE ?", "DAN DOUGHTY"])

and it finds the user with the name "Dan Doughty" on development server but does not find that same user in Production on Heroku. There is a User with that name on both environments.

Uninitialized Constant error for local gem during production assets precompile rake task

Posted: 20 Sep 2016 07:32 AM PDT

I am trying to integrate galetahub/ckeditor in my forums, tried to install from git in bundle but some problem as git command not detected in elastic beanstalk production even though I included git package in .elasticbeanstalk/config.yml. Also, needed to change some parameters for using git, bundle for installing gems. So, I cloned the gem to myvendor/gems and change path to local

so in Gemfile included,

gem 'ckeditor', '4.5.10', :path => File.join(File.dirname(__FILE__), 'vendor', 'gems', 'ckeditor')  

after deploying it installed but during assets precompile task, its not detecting module , In development environment everything is working fine.

eb logs error is

export RUBY_VERSION=2.3.1;    export GEM_ROOT="/opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0";'    +++ export RUBY_ENGINE=ruby    +++ RUBY_ENGINE=ruby    +++ export RUBY_VERSION=2.3.1    +++ RUBY_VERSION=2.3.1    +++ export GEM_ROOT=/opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0    +++ GEM_ROOT=/opt/rubies/ruby-2.3.1/lib/ruby/gems/2.3.0    ++ ((  0 != 0  ))    + cd /var/app/ondeck    + su -s /bin/bash -c 'bundle exec /opt/elasticbeanstalk/support/scripts/check-for-rake-task.rb assets:precompile' webapp    + '[' false == true ']'    + su -s /bin/bash -c 'bundle exec rake assets:precompile' webapp    rake aborted!    NoMethodError: undefined method `setup' for Ckeditor:Module    /var/app/ondeck/config/initializers/ckeditor.rb:2:in `<top (required)>'    /var/app/ondeck/config/environment.rb:5:in `<top (required)>'    /opt/rubies/ruby-2.3.1/bin/bundle:23:in `load'    /opt/rubies/ruby-2.3.1/bin/bundle:23:in `<main>'    Tasks: TOP => environment    (See full trace by running task with —trace) (Executor::NonZeroExitStatus)  

How do I raise an exception in Rspec while running a method?

Posted: 20 Sep 2016 07:20 AM PDT

I have an ActiveRecord Transaction that I am trying to test, but I'm having some difficulty understanding exactly how to write my Rspec test. Here is an example of what I'm going for:

it "does not change the model count" do    expect(Model.count).to be(0)    expect {      MyClass.my_method(arg1, arg2)    }.to raise_error    expect(Model.count).to be(0)  end  

While my_method is running, there are several objects being saved to the DB. I want to raise an exception while this method is running in order to invoke the transaction rollback.

What is the best way to go about raising this exception?

before_filter on Model with gsub method

Posted: 20 Sep 2016 07:24 AM PDT

I have a Customer model with has a attribute named contact_person. When a Customer gets created, imported as CSV or updated I want to remove "Dhr." or "Mvr." if it exists.

Currently i have a method:

def prefix_name    params[:customer][:contact_person].gsub("Dhr.", "")    50.times do      puts("test")    end  end  

And i'm running prefix_name with: before_filter :prefix_name, only: [:import, :create, :update]

In the server log i see that the method is being called but it does not change the params.

Create categories in rails App

Posted: 20 Sep 2016 07:25 AM PDT

I would like to create categories in my app: I got inspired by this question

But when @RailsGuy says: "Create some categories by categories controller and form (I don't think, I need to tell you that stuff, you are able to do it yourself)" I felt lost...

How and where do I create my list of categories? dogs, cats, birds... I saw that it could be done in the console but I will display a different pictures for each categories...

Here is my _form.html.slim

= simple_form_for @tuto do |f|    - if @tuto.errors.any?      #error_explanation        h2 = "#{pluralize(@tuto.errors.count, "error")} prohibited this tuto from being saved:"        ul          - @tuto.errors.full_messages.each do |message|            li = message    = f.hidden_field :user_id, value: current_user.id    = f.input  :title    = f.collection_select :category_id, Category.all, :id, :name, {prompt: "Choose Category"}    = f.input :content, as: :text, input_html: { rows: "15" }    = f.button :submit, "Save"  

my models:

tuto_model.rb

class Tuto < ActiveRecord::Base    acts_as_votable    belongs_to :user    belongs_to :category    validates :category, presence: true  end  

categoty_model.rb

class Category < ActiveRecord::Base    has_many :tutos  end  

schema.rb

ActiveRecord::Schema.define(version: 20160920133801) do      create_table "categories", force: :cascade do |t|      t.string   "name"      t.text     "description"      t.string   "image"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end      create_table "tutos", force: :cascade do |t|      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.string   "title"      t.text     "content"      t.integer  "user_id"      t.integer  "category_id"    end      add_index "tutos", ["user_id"], name: "index_tutos_on_user_id"      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.string   "first_name"      t.string   "last_name"      t.boolean  "admin"    end      add_index "users", ["email"], name: "index_users_on_email", unique: true    add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true      create_table "votes", force: :cascade do |t|      t.integer  "votable_id"      t.string   "votable_type"      t.integer  "voter_id"      t.string   "voter_type"      t.boolean  "vote_flag"      t.string   "vote_scope"      t.integer  "vote_weight"      t.datetime "created_at"      t.datetime "updated_at"    end      add_index "votes", ["votable_id", "votable_type", "vote_scope"], name: "index_votes_on_votable_id_and_votable_type_and_vote_scope"    add_index "votes", ["voter_id", "voter_type", "vote_scope"], name: "index_votes_on_voter_id_and_voter_type_and_vote_scope"    end  

thanks a lot for your help

Stack level too deep with ActiveSupport logger after ~ 475 requests

Posted: 20 Sep 2016 07:29 AM PDT

After around 475 requests my application produces a SystemStackError: stack level too deep exception. This is happening reliable and independent of which Controller and method are called. It also happens on multiple rails versions (4.2+, 5.0+) and in combination with multiple application servers (webrick, unicorn, puma). It only happens in development mode. Not in test and not in staging (which deploys to Tomcat with JRuby). Im using ruby-2.3.1 and jruby-9.1.2.0.

Here is the relevant part of the log:

2016-09-20 15:38:14 +0200: Rack app error handling request { GET /kw }  #<SystemStackError: stack level too deep>  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/rack-1.6.4/lib/rack/request.rb:361:in `split'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/rack-1.6.4/lib/rack/request.rb:361:in `split_ip_addresses'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/rack-1.6.4/lib/rack/request.rb:349:in `ip'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/actionpack-4.2.7.1/lib/action_dispatch/http/request.rb:226:in `ip'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/railties-4.2.7.1/lib/rails/rack/logger.rb:53:in `started_request_message'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/railties-4.2.7.1/lib/rails/rack/logger.rb:37:in `block in call_app'  /home/mwinter/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/logger.rb:427:in `add'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/activesupport-4.2.7.1/lib/active_support/logger.rb:77:in `add'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/activesupport-4.2.7.1/lib/active_support/logger.rb:15:in `block (2 levels) in broadcast'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/activesupport-4.2.7.1/lib/active_support/logger.rb:16:in `block (2 levels) in broadcast'    ### above line repeated 483 times ###    /home/mwinter/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/logger.rb:490:in `info'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/railties-4.2.7.1/lib/rails/rack/logger.rb:37:in `call_app'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/railties-4.2.7.1/lib/rails/rack/logger.rb:20:in `block in call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/activesupport-4.2.7.1/lib/active_support/tagged_logging.rb:68:in `block in tagged'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/activesupport-4.2.7.1/lib/active_support/tagged_logging.rb:26:in `tagged'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/activesupport-4.2.7.1/lib/active_support/tagged_logging.rb:68:in `tagged'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/railties-4.2.7.1/lib/rails/rack/logger.rb:20:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/request_store-1.3.1/lib/request_store/middleware.rb:9:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/actionpack-4.2.7.1/lib/action_dispatch/middleware/request_id.rb:21:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/rack-1.6.4/lib/rack/methodoverride.rb:22:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/rack-1.6.4/lib/rack/runtime.rb:18:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/activesupport-4.2.7.1/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/rack-1.6.4/lib/rack/lock.rb:17:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/actionpack-4.2.7.1/lib/action_dispatch/middleware/static.rb:120:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/rack-1.6.4/lib/rack/sendfile.rb:113:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/railties-4.2.7.1/lib/rails/engine.rb:518:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/railties-4.2.7.1/lib/rails/application.rb:165:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/rack-1.6.4/lib/rack/content_length.rb:15:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/puma-3.6.0/lib/puma/configuration.rb:225:in `call'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/puma-3.6.0/lib/puma/server.rb:578:in `handle_request'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/puma-3.6.0/lib/puma/server.rb:415:in `process_client'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/puma-3.6.0/lib/puma/server.rb:275:in `block in run'  /home/mwinter/.rvm/gems/ruby-2.3.1@demo_foo_bar/gems/puma-3.6.0/lib/puma/thread_pool.rb:116:in `block in spawn_thread'      Segmentation fault (core dumped)  

I'm searching for direct solutions to the issue or ideas how to debug/find the cause of the error.

How to change normal form which is linked with active merchant to Braintree dropin-ui?

Posted: 20 Sep 2016 06:48 AM PDT

I am having a registration page where user will enter personal info along with credit card info. This credit card info is integrated with activemerchant and as well as this info is stored in the database.

This is my form:

<%= semantic_form_for(@account, :url => account_create_path, :html => { :multipart => true, :class => 'billing'}) do |f| %>       <div class="section section-first">        <%= f.inputs :for => :user do |u| %>          <h3>Account Information</h3>            <%= u.input :name, :input_html => {:placeholder => "Name", :value => @account.user.name} %>          <%= u.input :email, :input_html => {:placeholder => "Email", :value => @account.user.email} %>        <% end %>      </div>          <div class="section">              <%= f.inputs :for => :creditcard do |c| %>              <h3>Credit Card Information</h3>              <%= c.input :brand, :selected => @creditcard.brand.nil? ? "visa" : @creditcard.brand, :label => "Credit Card", :as => :select, :class => 'dropkick', :include_blank => false, :collection => Saas::Config.gateway == "bogus" ? [['Bogus', 'bogus']] : [['Visa', 'visa'], ['MasterCard', 'master'], ['American Express', 'american_express'], ['Discover', 'discover']] %>              <%= c.input :number, :input_html => { :placeholder => "Card Number"}, :label => "Card Number", :as => :numeric %>                <li class="select required" id="account_creditcard_expiration_input">                  <label for="account_creditcard_expiration">Card Expires On<abbr title="required">*</abbr></label>                <%= c.select :year, (Time.now.year .. 10.years.from_now.year), :selected => @creditcard.year.nil? ? Time.now.year : @creditcard.year, :class => 'dropkick dd-small' %>                <%= c.select :month, [['1 - January', 1], ['2 - February', 2], ['3 - March', 3], ['4 - April', 4], ['5 - May', 5], ['6 - June', 6], ['7 - July', 7], ['8 - August', 8], ['9 - September', 9], ['10 - October', 10], ['11 - November', 11], ['12 - December', 12]], :selected => @creditcard.month.nil? ? "1" : @creditcard.month, :class => 'dropkick' %>              </li>                <%= c.input :verification_value, :label => "CVV Code", :input_html => { :placeholder => "CVV Code", :value => @creditcard.verification_value,                  :type => "password",                  :class => 'short' } %>              <% end %>    <% end %>  

Now the fields like card number, expiry date, etc; in the above form has to be in braintree drop-in ui(here itself the credit card number is validated by braintree). How can I modify this form? Please help.

This is my model, account.rb:

 def valid_subscription?       return if errors.any?       self.build_subscription(:plan => @plan, :next_renewal_at => @plan_start, :creditcard => @creditcard, :address => @address, :affiliate => @affiliate)         @address.first_name = @creditcard.first_name        @address.last_name = @creditcard.last_name      self.subscription.store_card(@creditcard, :billing_address => @address.to_activemerchant)      if !subscription.valid?        errors.add(:base, "Error with payment: #{subscription.errors.full_messages.to_sentence}")        return false      end    end  

accounts_controller:

class AccountsController < ApplicationController      before_filter :build_account, :only => [:new, :create]    before_filter :build_user, :only => [:new, :create]    before_filter :load_billing, :only => [:new, :create, :billing]    def create      @address.first_name = @creditcard.first_name      @address.last_name = @creditcard.last_name      @account.address = @address      @account.creditcard = @creditcard      if @account.new_record?        if @account.save          flash[:notice] = 'Account was created.'          bypass_sign_in(@user)          redirect_to session[:previous_url] || user_reports_path(@user)        else          render :action => 'new'        end      else        @user.account_id = @account.id        if @user.save          flash[:notice] = 'User was created.'          bypass_sign_in(@user)          redirect_to session[:previous_url] || user_reports_path(@user)        else          render :action => 'new'        end      end    end      def billing      @user = current_user      @account = Account.find(params[:id])      if request.put?        @address.first_name = @creditcard.first_name        @address.last_name = @creditcard.last_name        puts @address.first_name        if @creditcard.valid? & @address.valid?         if @subscription.store_card(@creditcard, :billing_address => @address.to_activemerchant, :ip => request.remote_ip)           flash[:notice] = "Your billing information has been updated."           redirect_to settings_path(@user)         end        end      end    end    protected      def resource      @account ||= current_account    end      def build_account      @account = params[:account_name].blank? ? Account.new : Account.find_by_name(params[:account_name])    end      def build_user      @account.user = @user = User.new(params[:account].blank? ? nil : params[:account][:user])    end      def load_billing      @creditcard = ActiveMerchant::Billing::CreditCard.new(params[:account].blank? ? {} : params[:account][:creditcard])      @address = SubscriptionAddress.new(params[:account].blank? ? {} : params[:account][:address])    end    end  

This is another model associated with account model, subscription.rb:

class Subscription < ActiveRecord::Base      attr_accessor :creditcard, :address    def store_card(creditcard, gw_options = {})      # Clear out payment info if switching to CC from PayPal      destroy_gateway_record(paypal) if paypal?        @response = if billing_id.blank?        gateway.store(creditcard, gw_options)      else        gateway.update(billing_id, creditcard, gw_options)      end        if @response.success?        if active_card = @response.params['active_card']          # Stripe token-based response          self.card_number = "XXXX-XXXX-XXXX-#{active_card['last4']}"          self.card_expiration = "%02d-%d" % [active_card['exp_month'], active_card['exp_year']]        else          self.card_number = creditcard.display_number          self.card_expiration = "%02d-%d" % [creditcard.expiry_date.month, creditcard.expiry_date.year]        end        set_billing      else        errors.add(:base, @response.message)        false      end    end      def card_storage        self.store_card(@creditcard, :billing_address => @address.to_activemerchant) if @creditcard && @address && card_number.blank?      end      def set_billing        self.billing_id = @response.token      end    end  

production.rb:

 config.after_initialize do      ActiveMerchant::Billing::Base.mode = :production      ::GATEWAY = ActiveMerchant::Billing::AuthorizeNetGateway.new(        :login => "xxxxxxx",        :password => "xxxxxxxxxxxxxx"    )    end  

Ruby's Virtus gem vs attr_accessor

Posted: 20 Sep 2016 07:00 AM PDT

I am looking at the Virtus gem used in a few tutorials about Service object in Ruby. In the github page, https://github.com/solnic/virtus, it gives the following example.

Using Virtus with Classes

You can create classes extended with Virtus and define attributes:

class User   include Virtus.model    attribute :name, String       attribute :age, Integer       attribute :birthday, DateTime   end    user = User.new(:name => 'Piotr', :age => 31) user.attributes # => { :name => "Piotr", :age => 31, :birthday => nil }    user.name # => "Piotr"    user.age = '31' # => 31 user.age.class # => Fixnum    user.birthday = 'November 18th, 1983' # => #<DateTime: 1983-11-18T00:00:00+00:00 (4891313/2,0/1,2299161)>    # mass-assignment user.attributes = { :name => 'Jane', :age => 21 } user.name # => "Jane" user.age  # => 21  

I can see how the example works, but would like to understand how is this different than just defining attr_accessors in Ruby? If I have to explain to someone, the benefit of including the Virtus gem and what it does in a couple of lines, what would it be?

Query nested jsonb Postgres column

Posted: 20 Sep 2016 07:18 AM PDT

I have a metadata column of type jsonb.

I know how to check whether it contains a specific key:

obj = Model.create  obj.metadata = {"foo"=>"1", "bar"=>{"baz"=>{"qux"=>2}}}    Model.where("(metadata->'bar') IS NOT NULL") # returns obj  

I wonder, how would I check if there is baz key in obj.metadata['bar'] and, if I had, for deeper nested keys?

Building a 3D model Database - Preferably MySql/Postgres/MongoDB

Posted: 20 Sep 2016 06:38 AM PDT

I am currently working on creating a library of 3D models created till date by our in-house 3D modellers using Unity3D/Maya/3ds Max, for further analysis and keeping track of each.

So, my question is how to go about storing them?

  1. So should I store them in a database or use some kind of storage like AWS S3. They are to be stored in .fbx format. Once stored I would want to perform operations on them, like viewing them online, download etc.

  2. Is there any other way/some kind of best practice to do the same

Rails - mysql2 installation error

Posted: 20 Sep 2016 07:17 AM PDT

I have recently installed rvm to use rails5 along with rails3.x version in my current system. When i tried to create new rails5 application, i have got the below error

Could not find proper version of railties (3.2.13) in any of the sources  Run `bundle install` to install missing gems.  

And when i try to do bundle install, i got stuck with this

gem install mysql2 -v '0.3.11'  Building native extensions.  This could take a while...  /home/himanth/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/ext/builder.rb:73: warning:     Insecure world writable dir /home/himanth/.rvm/gems in PATH, mode 040777  ERROR:  Error installing mysql2:  ERROR: Failed to build gem native extension.    /home/himanth/.rvm/rubies/ruby-2.3.1/bin/ruby extconf.rb  checking for rb_thread_blocking_region()... no  checking for rb_wait_for_single_fd()... yes  checking for mysql.h... yes  checking for errmsg.h... yes  checking for mysqld_error.h... yes  creating Makefile    make "DESTDIR=" clean    make "DESTDIR="  compiling mysql2_ext.c  In file included from ./client.h:11:0,               from ./mysql2_ext.h:39,               from mysql2_ext.c:1:  /home/himanth/.rvm/rubies/ruby-2.3.1/include/ruby-2.3.0/ruby/backward/rubysig.h:14:2: warning: #warning rubysig.h is obsolete [-Wcpp]  In file included from ./mysql2_ext.h:39:0,               from mysql2_ext.c:1:  ./client.h: In function 'rb_thread_blocking_region':  ./client.h:23:3: error: 'TRAP_BEG' undeclared (first use in this function)  ./client.h:23:3: note: each undeclared identifier is reported only once for each function it appears in  ./client.h:25:3: error: 'TRAP_END' undeclared (first use in this function)  mysql2_ext.c: At top level:  ./client.h:16:1: warning: 'rb_thread_blocking_region' defined but not used [-Wunused-function]  make: *** [mysql2_ext.o] Error 1    make failed, exit code 2    Gem files will remain installed in /home/himanth/.rvm/gems/ruby-2.3.1@rails5/gems/mysql2-0.3.11 for inspection.  Results logged to /home/himanth/.rvm/gems/ruby-2.3.1@rails5/extensions/x86_64-linux/2.3.0/mysql2-0.3.11/gem_make.out    An error occurred while installing mysql2 (0.3.11), and Bundler cannot continue.  Make sure that `gem install mysql2 -v '0.3.11'` succeeds before bundling.  

Got stuck with this for quite some time, any help would be much appreciated.

How to DRY scopes when mimicking different operators

Posted: 20 Sep 2016 06:08 AM PDT

Given

models/post.rb

class Post < ActiveRecord::Base    scope :deadline_eq, ->(date) { where("updated_at + (deadline_days * '1 day'::INTERVAL) = ?", date }    scope :deadline_not_eq, ->(date) { where("updated_at + (deadline_days * '1 day'::INTERVAL) != ?", date }    scope :deadline_lt, ->(date) { where("updated_at + (deadline_days * '1 day'::INTERVAL) < ?", date }    scope :deadline_gt, ->(date) { where("updated_at + (deadline_days * '1 day'::INTERVAL) > ?", date }    scope :deadline_lteq, ->(date) { where("updated_at + (deadline_days * '1 day'::INTERVAL) <= ?", date }    scope :deadline_gteq, ->(date) { where("updated_at + (deadline_days * '1 day'::INTERVAL) >= ?", date }  end  

So far, my DRYer version:

class Post < ActiveRecord::Base    DEADLINE_SQL = "updated_at + (deadline_days * '1 day'::INTERVAL)"      scope :deadline_eq, ->(date) { where("#{DEADLINE_SQL} = ?", date }    scope :deadline_not_eq, ->(date) { where("#{DEADLINE_SQL} != ?", date }    scope :deadline_lt, ->(date) { where("#{DEADLINE_SQL} < ?", date }    scope :deadline_gt, ->(date) { where("#{DEADLINE_SQL} > ?", date }    scope :deadline_lteq, ->(date) { where("#{DEADLINE_SQL} <= ?", date }    scope :deadline_gteq, ->(date) { where("#{DEADLINE_SQL} >= ?", date }  end  

Question

  1. Is there a better way to DRY(Dont Repeat Yourself)-up the above? Preferrably something that is compatible for the following question

  2. I know that virtual attributes cannot be used inside an SQL query, but is there, perhaps a gem, or a way to DRY this up in such a way that I could achieve hopefully something close to the following:

    Post.where(deadline: Date.tomorrow)  Post.where('deadline > ?', Date.tomorrow)    # instead of  Post.deadline_eq(Date.tomorrow)  Post.deadline_gt(Date.tomorrow)  

NOTE

  1. I can create another column deadline which I could update the value whenever the Post record is updated, but this is not my question, and I am just recreating/simplifying this Post table from an actual more complex table.
  2. I need these scopes for my API using ransack gem.

Fetching complete HTML page (including AJAX responses) in Ruby

Posted: 20 Sep 2016 06:22 AM PDT

I am trying to crawl an e-commerce catalogue, where products data is loaded using Ajax responses.

Thus, the content in response using get request is incomplete (partial data).

I am using Ruby's default HTTP library for fetching & Nokogiri for parsing.

Is there any way, in which I can initiate a request & record the response after some delay ?

Why some Ruby constants (classes, modules) should be explicitly required in Rails?

Posted: 20 Sep 2016 06:38 AM PDT

There seems to be two types of classes in ruby, one type I don't need to require they're always accessible (like Float, Array, Hash, etc.). They are a part of ruby and this is expected.

But there are also some constants that are not accessible unless explicitly required (like REXML, Observable, YAML). They are part of Ruby too and I would expect to be able to access them without require.

Why these constants are not available without require?

In Rails guides it is not recommended to explicitly require anything as this messes up Rails autoload mechanism. If these constants need to be required anyway, what is the best way to do it?

Should I use require or require_dependency?

Should I use require at the top of the file where the constant is used or should I do it globally somehow?

EDIT: Also, since constants availability depends on the loading order it is easy to forget to require some file and it will not break until load order changes somehow. What is the best way to not face such error except being extra alert about every constant you use?

Pinterest save not fetching all images in rails app

Posted: 20 Sep 2016 06:01 AM PDT

I have a rails application where I am trying to implement pinterest save button so that users can pin images from the blogs with urls linking to my site.

I have added the following code in views:

single_blog.html.haml

%li    %a.inline-block.pin-icon{:href => "https://www.pinterest.com/pin/create/button/"}      %i.fa.fa-pinterest-square.fa-2x  

I have also added script as follows:

%script{:async => "", :defer => "defer", :src => "//assets.pinterest.com/js/pinit.js"}  

Now when I click on the pin it button a window pops up with images (which also doesn't include all images from the blog).

I am able to pin the image that I select from available images. I have two questions.

  1. Why are all images not coming in pinterest window ?
  2. How can I know that an image has been successfully pinned so that I can update a counter or call a function that does it in jquery ?

if inside where query on rails

Posted: 20 Sep 2016 05:57 AM PDT

i have this query:

  def self.search(nombre,zona,tipoActividad,fechaInicio,fechaFin,nombreProfesor)        where("nombre) iLIKE ? or contenido iLIKE ? or descripcion iLIKE ? ", "%#{nombre}%", "%#{nombre}%","%#{nombre}%")        .where("lugar iLIKE ?", "%#{zona}%")        .where("tipo_actividad iLIKE ?", "%#{tipoActividad}%")        .where(['fecha_inicio >= ?', fechaInicio]) ***if !fechaInicio.blank?***        .where(['fecha_fin <= ?', fechaFin]) ***if !fechaFin.blank?***        .joins(:user).where("users.lastname iLIKE ?", "%#{nombreProfesor}%")    end  

I have the problem when i have to filter by fecha_fin and fecha_inicio. i need to filter by them only if the parameters are present. How can I re-change the query yo be ok?

Thanks.

How can i resolve this error? in Array

Posted: 20 Sep 2016 06:05 AM PDT

I have the data likes below in my model.

Mytable id:1,load_id:1,truck_id:1,  Mytable id:2,load_id:1,truck_id:2,  Mytable id:3,load_id:1,truck_id:3,  Mytable id:4,load_id:1,truck_id:4,  Mytable id:5,load_id:2,truck_id:5,  Mytable id:6,load_id:3,truck_id:5,  Mytable id:7,load_id:4,truck_id:5,  Mytable id:8,load_id:5,truck_id:5  

Within this i want to get the data based on uniqueness of load_id & truck_id to show in a index page.

(example:Mytable id:1,load_id:1,truck_id:1 & Mytable id:5,load_id:2,truck_id:5,)  

How is it possible in ruby?

Compressing images in CarrierWave uploader

Posted: 20 Sep 2016 05:46 AM PDT

I want to create a copy(which will be in webp version ) of uploaded image. how can i achieve this? directory should be same as original image. How does carrierwave determines the folder of uploaded image? I think it is following uploades/{entityId}/{modelId}/filename pattern

ps - I can create copy but it is not going in same folder.

Rspec `allow` not preventing method evaluation

Posted: 20 Sep 2016 06:09 AM PDT

Ran into an issue where allow is not stubbing a class method. I know this because if I stick a pry in the inner_method below, rspec will halt @ it during evaluation of the test. This behavior ONLY happens when the returned value is a factory_girl factory

example:

context '.wrapping_method returns inner value' do     it 'returns a value' do       allow(Thing).to receive(:method).and_return 'what'       expect(Thing.wrapping_method).to eql 'what'     end  end  

Thing class structure could be considered:

class Thing do     def self.wrapping_method        innerMethod || = 'nothing from inner'     end       def self.inner_method         # do some sort of thing here and return a value         binding.pry # <= eval reaches this     end  end  

It should be noted that other apps I have do not perform like this, and i am stumped as to what is different here.

How to add a switch toggle button to simple form in rails

Posted: 20 Sep 2016 05:49 AM PDT

I'm using Rails 4 and Simple Form with Bootstrap.

I want that my checkbox will not like that:

<%= c.input :my_bool_field, label: false, class: "form-control" %>  

enter image description here

but something like that (I have the CSS for that)

<label class="switch switch-primary">      <input type="checkbox" />      <span></span>  </label>  

enter image description here

I know I can use simple_form wrappers, but I find them a little bit confusing.. Can someone help me up creating the checkbox with that styling?

Rails: Disable automatic etag header for specific action

Posted: 20 Sep 2016 05:31 AM PDT

Is it possible to disable automatic etag header generation in rails for a specific action?

I tried to set response.etag = nil in the action, in an after_filter and in a before_filter. None of them have worked.

before save callback for boolean field

Posted: 20 Sep 2016 06:05 AM PDT

The before_save callback should update expired field value to true or false based on the code below:

class Package < ActiveRecord::Base    before_save :update_availabiltiy      def update_availabiltiy      self.expired = date_end.to_date < Date.today    end  end  

but it won't work unless the value of this field is the same as stored one, in example: if this field is true in DB and the condition in callback will evaluate to true, record will be saved, otherwise controller will return 400

Started PUT "/api/venues/bogan-and-sons/packages/delicious-package" for ::1 at 2016-09-20 15:20:03 +0300  Processing by Api::PackagesController#update as JSON    Parameters: {"package"=>    {"date_start"=>"2016-08-27T00:00:00.000-04:00", "date_end"=>"2016-12-30, ...}  }  (0.2ms)  BEGIN  (0.1ms)  ROLLBACK  Completed 400 Bad Request in 81ms (Views: 0.6ms | ActiveRecord: 17.8ms)  

object.errors returns empty array, so no actual error on object is present.

Update for Andrey:

[31, 40] in /Users/srosca/projects/venuezz/app/models/package.rb     31:     !expired || (Date.today <= self.date_end.to_date)     32:   end     33:      34:   def update_availabiltiy     35:     byebug  => 36:     self.expired = date_end.to_date < Date.today     37:   end     38:      39:   def calculate_discount     40:     if discount_price  (byebug) expired  true  (byebug) date_end.to_date < Date.today  false  (byebug) self.expired = date_end.to_date < Date.today  false  (byebug) expired  false  

Rails elasticsearch mapping set alias for fields

Posted: 20 Sep 2016 05:18 AM PDT

In my rails app, I already have jbuilder with already defined JSON keys, eg:

products: {      id: 1,      product_name: "Scarf",      vendor_name: "Vendor A",      is_available: true,      price: "$120"  }  

Let's say in my Product model object, it doesn't have product_name property.

But I want the returned JSON for product.name from Elasticsearch is product_name. How do I do that?

My attempts is to use custom method in my model like so:

def as_indexed_json(options = {})    self.as_json(      only: [:id, :is_available, :vendor_name, :product_name, :price],      methods: [:product_name],    )  end    def product_name    self.name  end  

But I think the elasticsearch-rails gem has a better way to do it. I can't find it anywhere on the repo documentation.

Anyone has the same issue?

Thanks in advance :)

Validating data from model that has_many LineItems in Rails5

Posted: 20 Sep 2016 05:15 AM PDT

I have

class Product < ApplicationRecord      scope :stuffa,  -> { where(product_type: 'S') }      scope :stuffb, -> { where(product_type: 'D') }  end      class Consumption < ActiveRecord::Base  end    class AConsumption < Consumption      has_many :stuffa_line_items, foreign_key: "consumption_id", class_name:"StuffakLineItem", dependent: :delete_all    end    class BConsumption < Consumption      has_many :stuffb_line_items, foreign_key: "consumption_id", class_name:"StuffbkLineItem", dependent: :delete_all    end    class LineItem < ActiveRecord::Base  end    class StuffaLineItem < LineItem      belongs_to :product, -> { stuffa }, class_name: "Product"  end    class StuffbLineItem < LineItem      belongs_to :product, -> { stuffb }, class_name: "Product"  end  

This seems however a little bit too complex. The beef here is that I need two different consumptions that have multiple lineitems. The lineitems are related to products so that only product type A can be a lineitem in AConsumption and product type B can be line in BConsumption. Now I have also separate lineitem models that actually do the validation for this. Would there be any other way to validate product in the linetype from the Consumption model? The idea would be get rid of separate lineitem models and just use one LineItem model.

RoR: Enums, how to list recipients of a message based on them

Posted: 20 Sep 2016 06:41 AM PDT

I have an application that allows a user to send a message to other users. I have two user types defined as enums in user rb- teacher and student:

enum access_level: [:student, :teacher]  

I am wondering how to get the desired recipients to appear in a list in the view (below) so that a teacher can only send to students or the other way round.

In my messages controller I have:

class MessagesController < ApplicationController    before_action :authenticate_user!      def new      @chosen_recipient = User.find_by(id: params[:to].to_i) if params[:to]    end      def create      recipients = User.where(id: params['recipients'])      conversation = current_user.send_message(recipients, params[:message][:body], params[:message][:subject]).conversation      flash[:success] = "Message has been sent!"      redirect_to conversation_path(conversation)    end  end  

And my conversations controller:

class ConversationsController < ApplicationController    before_action :authenticate_user!    before_action :get_mailbox    before_action :get_conversation, except: [:index, :empty_trash]    before_action :get_box, only: [:index]      def index      if @box.eql? "inbox"        @conversations = @mailbox.inbox      elsif @box.eql? "sent"        @conversations = @mailbox.sentbox      else        @conversations = @mailbox.trash      end        @conversations = @conversations.paginate(page: params[:page], per_page: 10)    end      def show    end      def mark_as_read      @conversation.mark_as_read(current_user)      flash[:success] = 'The conversation was marked as read.'      redirect_to conversations_path    end      def reply      current_user.reply_to_conversation(@conversation, params[:body])      flash[:success] = 'Reply sent'      redirect_to conversation_path(@conversation)    end      def destroy      @conversation.move_to_trash(current_user)      flash[:success] = 'The conversation was moved to trash.'      redirect_to conversations_path    end      def restore      @conversation.untrash(current_user)      flash[:success] = 'The conversation was restored.'      redirect_to conversations_path    end      def empty_trash      @mailbox.trash.each do |conversation|        conversation.receipts_for(current_user).update_all(deleted: true)      end      flash[:success] = 'Your trash was cleaned!'      redirect_to conversations_path    end      private      def get_mailbox      @mailbox ||= current_user.mailbox    end      def get_conversation      @conversation ||= @mailbox.conversations.find(params[:id])    end      def get_box      if params[:box].blank? or !["inbox","sent","trash"].include?(params[:box])        params[:box] = 'inbox'      end      @box = params[:box]    end  end  

My view (messages/_form.html.erb):

<%= form_tag messages_path, method: :post do %>    <div class="form-group">      <%= label_tag 'message[subject]', 'Subject' %>      <%= text_field_tag 'message[subject]', nil, class: 'form-control', required: true %>    </div>      <div class="form-group">      <%= label_tag 'message[body]', 'Message' %>      <%= text_area_tag 'message[body]', nil, cols: 3, class: 'form-control', required: true %>    </div>      <div class="form-group">      <%= label_tag 'recipients', 'Choose recipients' %>      <%= select_tag 'recipients', recipients_options(@chosen_recipient), multiple: true, class: 'form-control chosen-it' %>    </div>      <%= submit_tag 'Send', class: 'btn btn-primary' %>  <% end %>  

How would I get the list to appear based on the enum attribute associated with the user? A teacher could only see students for example.

Appreciate any guidance. Thanks.

ArgumentError in Users#index

Posted: 20 Sep 2016 05:51 AM PDT

Showing /home/bdme551/bdme21/app/views/users/index.html.erb where line #4 raised:

The @users variable appears to be empty. Did you forget to pass the collection object for will_paginate? Extracted source (around line #4):

<h1>All users</h1>    <%= will_paginate %>    <ul class="users">    <%= render @users %>  

I know I am missing something. But, I couldn't figure it out. Can someone help me, please? Thank you.

Users_controller

def index      @users = User.paginate(page: params[:page])  end  

Console log

ActionView::Template::Error (The @users variable appears to be empty. Did you forget to pass the collection object for will_paginate?):      1: <% provide(:title, 'All users') %>      2: <h1>All users</h1>      3:       4: <%= will_paginate @users %>      5:       6: <ul class="users">      7:   <%= render @users %>    app/views/users/index.html.erb:4:in `_app_views_users_index_html_erb___3148545551871597623_70202198493380'    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (5.2ms)    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.3ms)    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (26.1ms)  DEPRECATION WARNING: #original_exception is deprecated. Use #cause instead. (called from process_request at /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:97)    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/index.html.erb    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_markup.html.erb (0.5ms)    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/console.js.erb within layouts/javascript    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.4ms)    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.6ms)    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/style.css.erb within layouts/inlined_string    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.7ms)    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/console.js.erb within layouts/javascript (19.9ms)    Rendering /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/main.js.erb within layouts/javascript    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.6ms)    Rendered /home/bdme551/.rvm/gems/ruby-2.3.1/gems/web-console-3.1.1/lib/web_console/templates/index.html.erb (35.5ms)  

Ruby on Rails Activeadmin - Custom select list

Posted: 20 Sep 2016 04:01 AM PDT

In my Rails application, I have the following models:

class Organization < ActiveRecord::Base    belongs_to :cooperation, foreign_key: "id"  end    class Cooperation < ActiveRecord::Base    has_one :organization  end  

A cooperation have two organization's ids. I need the name of the organizations, but i only can get the ids

In the activeAdmin form:

form multipart: true do |f|        f.inputs "R. Organizacions" do          f.input :nameC, :as => :select, :collection =>              Cooperation.all.map {|cooperation|                [cooperation.organization1+" "+cooperation.organization2, cooperation.id] },              label: "Name"  (...)  

"cooperation.organization1" and "cooperation.organization2", returns the ids of the organizations, but i dont know how i can get the names with the :select

I need something like this SQL Statement:

SELECT  "organizations".name    FROM "organizations" , "cooperations"    WHERE "organizations"."id" = "cooperations"."id"  

Run two ruby scripts from rake task

Posted: 20 Sep 2016 03:59 AM PDT

So this is a simple rake task:

task :map_reduce do    puts 'Running map reduce scripts...'    ruby "#{PADRINO_ROOT}/map_reduce/raw_visits_map.rb '03-08-2016' 90" && ruby "#{PADRINO_ROOT}/map_reduce/raw_visits_reducer.rb"  end  

The first script outputs the result in STDOUT to be further read by the so called 'reducer'. In the terminal, I am able to run those two scripts like:

ruby first_script.rb param1 param2 | ruby second_script.rb  

So the second script can read from STDOUT like

res = ARGF  

But how can I line up the 2 executions inside that rake task?

How I wrongfully tried it's not working.

Validate Numericality Conditions on English & Arabic Numbers

Posted: 20 Sep 2016 05:33 AM PDT

I'm using the following code to validate numericality in Rails:

validates :number, :numericality => {:greater_than_or_equal_to => 500}  

And it works well, but then I added regex to allow Arabic numbers like this:

validates :number, :format =>{:with => /[0-9\u0660-\u0669]*/}  

Here it accepts Arabic numbers but the condition greater_than_or_equal_to => 500 is working only on English numbers and I need it to support Arabic numbers too.

No comments:

Post a Comment