Monday, August 1, 2016

Rails, Is there a way to generate Unit Tests from Existing Controllers and methods defined in them? | Fixed issues

Rails, Is there a way to generate Unit Tests from Existing Controllers and methods defined in them? | Fixed issues


Rails, Is there a way to generate Unit Tests from Existing Controllers and methods defined in them?

Posted: 01 Aug 2016 07:56 AM PDT

I was wondering if there is a script that can take existing codebase and generate unit tests for each method in controllers. By default all would be passing since they would be empty and i can remove tests i for methods i dont feel important.

This would save huge time and increase testing. Since i'd have to define only what each method should output and not boilerplate that needs to be written.

Rendering two collections in rails

Posted: 01 Aug 2016 07:48 AM PDT

I am having trouble rendering two collections in rails. Essentially, I want the :html rendering the following collections to a string in one :html call:

:html => render_to_string( :partial => "day_notes", :locals => {:day_notes => day_notes, :date => date} )  :html => render_to_string( :partial => "events", :locals => {:events => events, :date => date} )  

What would be the format for doing such a thing? Any and all help is appreciated. Cheers~

rails jquery disable the download button until the form is saved

Posted: 01 Aug 2016 07:56 AM PDT

view

I have created a form which has save and download button. I want the save button to be disabled until completion of all fields and download button to be disabled until the form is being saved.

- content_for :javascript_includes do    = javascript_include_tag "dropdown.js", "business.js", "bootstrap-toggle.min.js"  .col-sm-12    .main-login.main-center.customer_details  = nested_form_for(@customer_detail) do |f|    - all_views_side_error_messages!(@customer_detail)    .form-alignment      .fieldset        .row          .col-sm-12          = f.label :customer_name,"Organisation/Customer Name", class: "col-sm-3 control-label text-right"          = f.text_field :customer_name, autofocus: true, class: "col-sm-3"          = f.label :residential_type,"Residential Type", class: "col-sm-3 control-label text-right"          = f.check_box :residential_type, autofocus: true, "data-width" => "200", class: "toggle-two-resident select-resident col-sm-3"      %br        .fieldset        .row          .col-sm-12          = f.label :customer_id,"Customer ID", class: "col-sm-3 control-label text-right"          = f.text_field :customer_id, autofocus: true, class: "col-sm-3"          = f.label :attention_to,"Attention To", class: "col-sm-3 control-label text-right"          = f.text_field :attention_to, autofocus: true, class: "col-sm-3"      %br        .fieldset        .row          .col-sm-12          = f.label :address,"Address", class: "col-sm-3 control-label text-right"          = f.text_area :address, autofocus: true, class: "col-sm-3"          = f.label :city,"City", class: "col-sm-3 control-label text-right"          = f.text_field :city, autofocus: true, class: "col-sm-3"      %br        .fieldset        .row          .col-sm-12          = f.label :pin_code,"Pin Code", class: "col-sm-3 control-label text-right"          = f.text_field :pin_code, autofocus: true, class: "col-sm-3"          %div{id: 'state_field'}            = f.label :state,"State", class: "col-sm-3 control-label text-right"            = f.select(:state, options_for_select(State.collect_state),{},{class: "selectpicker col-sm-3 column-width-change", prompt: "Select State", "data-live-search": "true"})          %div.hide{id: 'country_field'}            = f.label :country,"Country", class: "col-sm-3 control-label text-right"            = f.select(:country, CountryList.collect_country_list,{}, {class: "selectpicker add_class_country dropdown_country col-sm-3 column-width-change", title: "select country", "data-live-search": "true"})        %br        .fieldset        .row          .col-sm-12          = f.label :email,"Email", class: "col-sm-3 control-label text-right"          = f.email_field :email, autofocus: true, class: "col-sm-3"          = f.label :contact_no,"Contact No", class: "col-sm-3 control-label text-right"          = f.text_field :contact_no, autofocus: true, class: "col-sm-3"      %br        .fieldset        .row          .col-sm-12          = f.label :website,"Website", class: "col-sm-3 control-label text-right"          = f.text_field :website, autofocus: true, class: "col-sm-3"          %div.hide{id: 'currency_field'}            = f.label :currency_type,"Currency Type", class: "col-sm-3 control-label text-right"            = f.select(:currency_type, CurrencyType.collect_currency_type,{},{class: "selectpicker dropdown_business column-width-change", prompt: 'Select', "data-live-search": "true"})          %div{id: 'change_resident'}            = f.label :business_type,"Business Type", class: "col-sm-3 control-label text-right"            = f.select(:business_type, BusinessType.collect_business_type,{},{class: "selectpicker dropdown_business column-width-change", prompt: 'Select', "data-live-search": "true"})            %br            %br        .fieldset        .row          .col-sm-12          = f.label :service_tax_reg_no,"Service tax Registration No", class: "col-sm-3 control-label text-right"          = f.text_field :service_tax_reg_no, autofocus: true, class: "col-sm-3"          = f.label :pan_no,"PAN No", class: "col-sm-3 control-label text-right"          = f.text_field :pan_no, autofocus: true, class: "col-sm-3"      %br        .fieldset        .row          .col-sm-12          = f.label :local_sales_tax_reg_no,"Local Sales Tax Registration No", class: "col-sm-3 control-label text-right"          = f.text_field :local_sales_tax_reg_no, autofocus: true, class: "col-sm-3"          = f.label :central_sales_tax_no,"Central Sales Tax Registration No", class: "col-sm-3 control-label text-right"          = f.text_field :central_sales_tax_no, autofocus: true, class: "col-sm-3"      %br        = render partial: 'customer_details/goods_address', locals: {customer_detail: @customer_detail}      %br        .fieldset        .row          .col-sm-12            = f.label :opening_bal,"Opening Balance if any?", class: "col-sm-3 control-label text-right"            = f.text_field :opening_bal, autofocus: true, class: "col-sm-3"            = f.label :business_center,"From which business center invoice is being raised?", class: "col-sm-3 control-label text-right business_center-alignment"            = f.select(:business_center, BusinessType.collect_business_type,{},{class: "selectpicker dropdown_business column-width-change", prompt: 'Select', "data-live-search": "true"})      %br          .fieldset        .row          .col-sm-3            = f.submit "Save", class: "btn btn-primary"          .col-sm-3            = f.submit "cancel", type: :reset, class: "btn btn-primary"          .col-sm-3            - if @customer_detail.save              = link_to "Download", download_csv_customer_detail_path(@customer_detail.id, format: "csv"), class: "btn btn-primary.disabled"          .col-sm-3            = link_to("Print", "javascript:print()", class: "btn btn-primary")
I dont know how to write conditions for it in the JS.can someone please help me.Thanks in advance

Getting a log of Rails API calls (and responses)

Posted: 01 Aug 2016 07:43 AM PDT

I've got a Rails application which also contains an API part (through the /api route).

This works but I would like to have one of the following options:

  • Have a rolling log (for example keep the last 100 calls and responses) and visualise this in the web application.
  • Have the option (in the web application) to enable monitoring and when it's enabled display all calls and responses that are made to the API.

I'm hoping I'm not the first to look for something like this. Are there any gems available that suit this purpose?

When JSON data posted in rails throws param is missing or the value is empty: stall

Posted: 01 Aug 2016 07:48 AM PDT

I have been trying post JSON data via POSTMAN but I get param is missing or the value is empty: stall. can someone please tell me where I'm going wrong ?

 def create     @stall = Stall.new(stall_params)           if @stall.save           render json: @stall, status: :created         else             render json: @stall.errors, status: :unprocessable_entity      end    end        private  def stall_params    params.require(:stall).permit(:name, :place)  end  

My Table contains only two columns name and place

Below is the log Processing by API::V1::StallsController#create as JSON Parameters: {"name"=>"trill", "place"=>"trill"} Completed 400 Bad Request in 0ms (ActiveRecord: 0.0ms)

ActionController::ParameterMissing (param is missing or the value is empty: stall): app/controllers/api/v1/stalls_controller.rb:47:in stall_params' app/controllers/api/v1/stalls_controller.rb:27:increate'

Rendered /home/goutham/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (7.4ms) Rendered /home/goutham/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (16.0ms) Rendered /home/goutham/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.9ms) Rendered /home/goutham/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (135.0ms)

Get fields from Ruby Model belonging to a certain Class

Posted: 01 Aug 2016 07:40 AM PDT

I am interested in getting all attributes or column_names from a Ruby Model which belong to a certain class. Not able to find a way to achieve it. Please let know if anyone has solution to it.

E.g.:  -Get all column_names belonging to class ActiveSupport::TimeWithZone    -Output:  ['created_at','updated_at','delivery_date','packed_date']  

Passing arguments from one action to another with ajax in ruby on rails

Posted: 01 Aug 2016 07:39 AM PDT

I create new payment

def new      @contract = Contract.find(session[:contract_id])      # Register card for user      @card_preregistration = MangoPay::CardRegistration.create({          UserId: current_user.mangopay_id,          Currency: "EUR",          CardType: "CB_VISA_MASTERCARD"        })      session[:card_id] = @card_preregistration['Id']      locals card_reg: @card_preregistration    end  

pass all data to url payment server with ajax.

register_card.coffee

jQuery ->    $('#payment-form').submit (e) ->      e.preventDefault()        $this = $(this)        mangoPay.cardRegistration.init        cardRegistrationURL: $("#CardRegistrationURL").val()        preregistrationData: $("#PreregistrationData").val()        accessKey: $("#AccessKey").val()        cardData = {        cardNumber: $("#card_number").val()        cardExpirationDate: $("#card_expiration_date").val()        cardCvx: $("#cardCvx").val()      }        mangoPay.cardRegistration.sendDataWithAjax(        # URL to capture response        "http://site:8080/finialize",        # Card data        cardData,        # Result Ajax callback        (data) ->          #console.log(data)        # Error Ajax callback        (xhr, status, error) ->           alert("Payment error : " + xhr.responseText + " (" + status + " - " + error + ")")        )      #cons  

After run method finialize_payment:

def finialize_payment      binding.pry      card_registration = MangoPay::CardRegistration.update(session[:card_id], {          RegistrationData: "data=#{params['data']}",          Tag: "custom tag"        })      end  

session[:card_id] is nill. How pass variable @card_preregistration from new to finialize_payment?

Rails routing: Changing the 'show' path for a resource

Posted: 01 Aug 2016 07:39 AM PDT

I would like to change the show path to make it more SEO friendly. The code below throws an error when trying to go to edit

routes.rb

resources :posts, :only => [:index, :new, :create, :update, :edit]

match "posts/:id/:league_name/:post_description", to: 'posts#show', :as => :post, via: :get

error

No route matches {:controller=>"posts", :action=>"show", :format=>nil, :id=>#<Post id: 1, title: "2 Pick Parlay", content: "<h1>Here you go</h1>\r\nStarting off the season right...", link: nil, created_at: "2016-07-31 21:45:40", updated_at: "2016-07-31 22:01:58", user_id: 2, league_id: 1, initial_status: nil, home_team: "", favorite: "", points: nil, visiting_team: "", event_datetime: "2016-09-09 00:30:00", spread_home: nil, spread_away: nil, total_points: nil, user_spread: nil, user_team_pick: nil, user_total_pick: nil, user_total_points: nil, user_line_source: nil, post_type: nil, event_id: 137, subscriber_only: false, release_at_gametime: false, is_parlay: true, flagged: false, weight: 1, post_description: "pick">}

When I take out the form_for on the edit page .. the page renders. So the problem must be in this code which is on the edit page

offending code in edit.haml.html

= form_for(@post) do |f| %h3 Title for write up = f.text_field(:title, :class => "field span8") %br %br %h3 Your analysis = f.text_area(:content, :class => "field span8", :rows => "5") <br/> = f.hidden_field(:league_id)
= f.hidden_field(:event_id) = f.hidden_field(:home_team) = f.hidden_field(:visiting_team) = f.hidden_field(:favorite) = f.hidden_field(:points) = f.hidden_field(:event_datetime)
%br %br
%h4 - if @picks_tweet_string && @just_this_post_tweet_string - if @just_this_post_tweet_string.size > 130 = link_to "Tweet these picks out now", "https://twitter.com/intent/tweet?text=#{@just_this_post_tweet_string}", confirm: "Click OK below. Then you may need to shorten the tweet to 140 characters. Most people remove the city name from the picks." - else
= link_to "Tweet these picks out now", "https://twitter.com/intent/tweet?text=#{@just_this_post_tweet_string}" %br
- if @picks_tweet_string.size > 130 = link_to "I want to tweet my current full card", "https://twitter.com/intent/tweet?text=#{@picks_tweet_string}", confirm: "Click OK below. Then you may need to shorten the tweet to 140 characters. Most people remove the city name from the picks." - else
= link_to "I want to tweet my current full card", "https://twitter.com/intent/tweet?text=#{@picks_tweet_string}"
%br %br
= f.submit "SUMBIT THIS WRITE-UP", class: 'btn-xlarge btn-block btn-primary' %br %br = f.submit "No additional write-up", class: 'btn-xlarge btn-block btn-primary'

Any ideas what is wrong with that?

Install gems on docker

Posted: 01 Aug 2016 07:02 AM PDT

I develop an app using rails and Docker. I faced an issue: when I run

docker-compose -f dcom-dev.yml run --user $(id -u)  web gem install google-api-client  

it runs good, but if I write to my Gemfile gem 'google-api-client' and then run

docker-compose -f dcom-dev.yml run --user $(id -u)  web bundle install  

it failes with several warnings like this:

Errno::ENOENT: No such file or directory @ rb_sysopen - /.gem/ruby/2.3.0/cache/memoist-0.14.0.gem  

and an error like this:

An error occurred while installing memoist (0.14.0), and Bundler cannot continue.  Make sure that `gem install memoist -v '0.14.0'` succeeds before bundling.  

If I run gem install manually, it works fine, but bundle install throws error about another gem (little-plugger). If I install the second gem manually, bundler throws message about the first gem (memoist) again and it repeats again and again. What could I do with this? Thanks in advance!

Ruby How to convert back binary string from smsc

Posted: 01 Aug 2016 06:49 AM PDT

my app work with SMSC, and i need to get involve in sms before it send,

i try to send from the mobile that string

"hello this is test"

And when I check the smsc I got this as binary string of my text:

userData = "c8329bfd06d1d1e939283d07d1cb733a"  

the encoding of this string is:

<Encoding:ASCII-8BIT>  

I know that probably this userData is in GSM encoding in binary-string

so how can i get from userData back the clear text string ?

this question is for english lang, because in Hebrew I can get back the string with this code:

[userData].pack('H*').force_encoding('utf-16be').encode('utf-8')

but in english i got error:

Encoding::InvalidByteSequenceError: "\xDA\xF3" followed by "u" on UTF-16BE  

What I was try is to detect the binary string with ICU, and I got:

"ISO-8859-1" and the language that detected is: 'PT', that very strange cause my languages is English or Hebrew.

anyway i got lost with encoding stuff, so i try to encode to each name of list from Encoding.list

but without luck until now

thanks in advance

Shmulik

How to schedule Sidekiq Woker.perform.now?

Posted: 01 Aug 2016 07:04 AM PDT

I have a worker with one perform class. In the controller I am calling up that worker class. When I call it up with worker.perform.now I see in console that perform method is being executed as I want it.

How to schedule this callup in controller, to be performed every day at ten o'clock?

PS: When I call worker.perform_async it doesn't do anything.

Rails transaction rollback does not happen if after_create fails

Posted: 01 Aug 2016 06:53 AM PDT

In my User model I have a after_created callback as

after_create :count_files  def count_files    errors[:base] << "error working"    errors.add(:base, "error working")            return false  end  

As you can see, I am always adding base errors and returning false always, but still user is created. I think, if after_create returns false then automatic rollback happens instead of saving data in database. But for my case, data is always saving in database and transaction rollback doesn't happen. Why is that? how can I prevent user from being created if my after_create fails?

RoR permitting non modal parameter

Posted: 01 Aug 2016 06:04 AM PDT

I'm having a hard time trying to understand how to permit non modal parameters.

I've read:

So, for a "normal" situation - let's say that I have a model Foo which has just one attribute bar:

# foo.rb  class Foo < ActiveRecord::Base    # bar, which is a integer  end    # views/foos/new.html.erb  <%= form_for @foo do |f| %>      <%= f.number_field :bar %>      <%= f.submit %>  <% end %>    #foos_controller.rb  def create      @foo = Foo.new(foo_params)      # ...  end    #...    private    def foo_params      params.require(:foo).permit(:bar)  end  

So, when I submit the form, the Foo will be created.


However, what if the bar attribute has some logic behind it that combines some non modal parameters? Let's say that bar is the sum of two parameters (bar = bar_1 + bar_2). Then the view and controller looks like:

# views/foos/new.html.erb  <%= form_for @foo do |f| %>      <%= f.number_field :bar_1 %>      <%= f.number_field :bar_2 %>      <%= f.submit %>  <% end %>    #foos_controller.rb  def create    bar_1 = params[:bar_1]    bar_2 = params[:bar_2]      if bar_1.present? && bar_2.present?      @foo = Foo.new      @foo.bar = bar_1.to_i + bar_2.to_i        if @foo.save        # redirect with success message      else        # render :new      end    else      # not present    end  end  

So the question is, do I also need to permit the bar_1 and bar_2 parameters? If I do, how do I permit them?

Heroku rejecting my git push due to SQLite3

Posted: 01 Aug 2016 07:44 AM PDT

Heroku keeps rejecting my pushes with this error:

 Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling.  remote:  !  remote:  !     Failed to install gems via Bundler.  remote:  !       remote:  !     Detected sqlite3 gem which is not supported on Heroku.  remote:  !     https://devcenter.heroku.com/articles/sqlite3  remote:  !  remote:  !     Push rejected, failed to compile Ruby app.  

I realize this is a common problem (I have looked at other threads) I have tried removing the sqlite3 gem from my Gemfile, I ran a bundle install and made sure that the sqlite3 gem was also out of my Gemfile.lock (which it was).
I also got rid of all references to sqlite3 from my database.yml and replaced them with Postgres:

#  default: &default    adapter: postgresql    encoding: unicode    database: store_development    pool: 5    timeout: 5000    development:      adapter: postgresql      encoding: unicode      database: store_development    # Warning: The database defined as "test" will be erased and  # re-generated from your development database when you run "rake".  # Do not set this db to the same as development or production.  test:    adapter: postgresql    encoding: unicode    database: store_test    production:    adapter: postgresql    encoding: unicode    database: store_development  

I'm lost any suggestions?

Here is my gemfile:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.5.1'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.1.0'  #bcrypt for for encrpytion  gem 'bcrypt', '~> 3.1', '>= 3.1.11'  #byebug  gem 'byebug', '~> 9.0', '>= 9.0.5'  # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks  gem 'turbolinks'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '~> 0.4.0', group: :doc  #paperclip for easy upload management  gem 'paperclip', '~> 4.3', '>= 4.3.6'  #bootstrap-sass  gem 'bootstrap-sass', '~> 3.3', '>= 3.3.6'  #searchkick  gem 'searchkick', '~> 1.2', '>= 1.2.1'  #paginate  gem 'will_paginate', '~> 3.1'  #paginate for bootstrap  gem 'bootstrap-will_paginate', '~> 0.0.10'  #Carrierwave  #gem 'carrierwave'  #Cloudinary  #gem 'cloudinary'  #Paperclip forcloudinary  gem 'paperclip-cloudinary'  #elasticsearch stuff  gem 'elasticsearch-rails'  gem 'elasticsearch-model'  #bonsi  gem 'bonsai-elasticsearch-rails', '~> 0.0.4'        group :development, :test do      end    group :development do    # Access an IRB console on exception pages or by using <%= console %> in views    gem 'web-console', '~> 2.0'    # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'    #db stuff    gem 'sqlite3'        end  group :production do    gem 'rails_12factor'    gem 'puma', '~> 3.4'    #postgresql    gem 'pg'  end  

I'll also include the whole Heroku rejection just for reference:

    remote: Compressing source files... done.  remote: Building source:  remote:   remote: -----> Ruby app detected  remote: -----> Compiling Ruby/Rails  remote: -----> Using Ruby version: ruby-2.2.4  remote: -----> Installing dependencies using bundler 1.11.2  remote:        Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment  remote:        Warning: the running version of Bundler is older than the version that created the lockfile. We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.  remote:        Fetching gem metadata from https://rubygems.org/.........  remote:        Fetching version metadata from https://rubygems.org/...  remote:        Fetching dependency metadata from https://rubygems.org/..  remote:        Using i18n 0.7.0  remote:        Using rake 11.1.2  remote:        Using json 1.8.3  remote:        Using minitest 5.8.4  remote:        Using thread_safe 0.3.5  remote:        Using builder 3.2.2  remote:        Using erubis 2.7.0  remote:        Using mini_portile2 2.0.0  remote:        Using rack 1.6.4  remote:        Using mime-types-data 3.2016.0221  remote:        Using arel 6.0.3  remote:        Using execjs 2.6.0  remote:        Using aws_cf_signer 0.1.3  remote:        Using bcrypt 3.1.11  remote:        Using bonsai-elasticsearch-rails 0.0.4  remote:        Using sass 3.4.22  remote:        Using will_paginate 3.1.0  remote:        Using coffee-script-source 1.10.0  remote:        Using thor 0.19.1  remote:        Using concurrent-ruby 1.0.1  remote:        Using orm_adapter 0.5.0  remote:        Using multi_json 1.11.2  remote:        Using multipart-post 2.0.0  remote:        Using hashie 3.4.3  remote:        Using elasticsearch-rails 0.1.9  remote:        Using mimemagic 0.3.0  remote:        Using pg 0.18.4  remote:        Using bundler 1.11.2  remote:        Using rails_serve_static_assets 0.0.5  remote:        Using rails_stdout_logging 0.0.5  remote:        Using tilt 2.0.2  remote:        Using rdoc 4.2.2  remote:        Using tzinfo 1.2.2  remote:        Using nokogiri 1.6.7.2  remote:        Using mime-types 3.0  remote:        Using autoprefixer-rails 6.3.6  remote:        Using uglifier 3.0.0  remote:        Using rack-test 0.6.3  remote:        Using warden 1.2.6  remote:        Using bootstrap-will_paginate 0.0.10  remote:        Using coffee-script 2.4.1  remote:        Using sprockets 3.6.0  remote:        Using elasticsearch-api 1.0.17  remote:        Using faraday 0.9.2  remote:        Using rails_12factor 0.0.3  remote:        Using sdoc 0.4.1  remote:        Using activesupport 4.2.5.1  remote:        Using loofah 2.0.3  remote:        Using mail 2.6.4  remote:        Using rest-client 1.6.7  remote:        Using bootstrap-sass 3.3.6  remote:        Using elasticsearch-transport 1.0.17  remote:        Using rails-deprecated_sanitizer 1.0.3  remote:        Using globalid 0.3.6  remote:        Using activemodel 4.2.5.1  remote:        Using climate_control 0.0.3  remote:        Using jbuilder 2.4.1  remote:        Using rails-html-sanitizer 1.0.3  remote:        Using cloudinary 1.2.0  remote:        Using rails-dom-testing 1.0.7  remote:        Using elasticsearch 1.0.17  remote:        Using activejob 4.2.5.1  remote:        Using cocaine 0.5.8  remote:        Using paperclip-cloudinary 1.1.0  remote:        Using actionview 4.2.5.1  remote:        Using elasticsearch-model 0.1.9  remote:        Using activerecord 4.2.5.1  remote:        Using searchkick 1.2.1  remote:        Using paperclip 4.3.6  remote:        Using actionpack 4.2.5.1  remote:        Using actionmailer 4.2.5.1  remote:        Using railties 4.2.5.1  remote:        Using sprockets-rails 3.0.4  remote:        Using coffee-rails 4.1.1  remote:        Using responders 2.1.2  remote:        Using jquery-rails 4.1.1  remote:        Using rails 4.2.5.1  remote:        Using sass-rails 5.0.4  remote:        Using turbolinks 2.5.3  remote:        Using devise 4.0.0  remote:        Installing sqlite3 1.3.11 with native extensions  remote:        Gem::Ext::BuildError: ERROR: Failed to build gem native extension.  remote:        /tmp/build_650c9daea9707f0830f7e2ecbfc558e2/vendor/ruby-2.2.4/bin/ruby -r ./siteconf20160801-197-lz2bsz.rb extconf.rb  remote:        checking for sqlite3.h... no  remote:        sqlite3.h is missing. Try 'port install sqlite3 +universal',  remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'  remote:        and check your shared library search path (the  remote:        location where your sqlite3 shared library is located).  remote:        *** extconf.rb failed ***  remote:        Could not create Makefile due to some reason, probably lack of necessary  remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may  remote:        need configuration options.  remote:        Provided configuration options:  remote:        --with-opt-dir  remote:        --without-opt-dir  remote:        --with-opt-include  remote:        --without-opt-include=${opt-dir}/include  remote:        --with-opt-lib  remote:        --without-opt-lib=${opt-dir}/lib  remote:        --with-make-prog  remote:        --without-make-prog  remote:        --srcdir=.  remote:        --curdir  remote:        --ruby=/tmp/build_650c9daea9707f0830f7e2ecbfc558e2/vendor/ruby-2.2.4/bin/$(RUBY_BASE_NAME)  remote:        --with-sqlite3-dir  remote:        --without-sqlite3-dir  remote:        --with-sqlite3-include  remote:        --without-sqlite3-include=${sqlite3-dir}/include  remote:        --with-sqlite3-lib  remote:        --without-sqlite3-lib=${sqlite3-dir}/lib  remote:        extconf failed, exit code 1  remote:        Gem files will remain installed in /tmp/build_650c9daea9707f0830f7e2ecbfc558e2/vendor/bundle/ruby/2.2.0/gems/sqlite3-1.3.11 for inspection.  remote:        Results logged to /tmp/build_650c9daea9707f0830f7e2ecbfc558e2/vendor/bundle/ruby/2.2.0/extensions/x86_64-linux/2.2.0-static/sqlite3-1.3.11/gem_make.out  remote:        An error occurred while installing sqlite3 (1.3.11), and Bundler cannot  remote:        continue.  remote:        Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling.  remote:        Bundler Output: Warning: the running version of Bundler is older than the version that created the lockfile. We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.  remote:        Fetching gem metadata from https://rubygems.org/.........  remote:        Fetching version metadata from https://rubygems.org/...  remote:        Fetching dependency metadata from https://rubygems.org/..  remote:        Using i18n 0.7.0  remote:        Using rake 11.1.2  remote:        Using json 1.8.3  remote:        Using minitest 5.8.4  remote:        Using thread_safe 0.3.5  remote:        Using builder 3.2.2  remote:        Using erubis 2.7.0  remote:        Using mini_portile2 2.0.0  remote:        Using rack 1.6.4  remote:        Using mime-types-data 3.2016.0221  remote:        Using arel 6.0.3  remote:        Using execjs 2.6.0  remote:        Using aws_cf_signer 0.1.3  remote:        Using bcrypt 3.1.11  remote:        Using bonsai-elasticsearch-rails 0.0.4  remote:        Using sass 3.4.22  remote:        Using will_paginate 3.1.0  remote:        Using coffee-script-source 1.10.0  remote:        Using thor 0.19.1  remote:        Using concurrent-ruby 1.0.1  remote:        Using orm_adapter 0.5.0  remote:        Using multi_json 1.11.2  remote:        Using multipart-post 2.0.0  remote:        Using hashie 3.4.3  remote:        Using elasticsearch-rails 0.1.9  remote:        Using mimemagic 0.3.0  remote:        Using pg 0.18.4  remote:        Using bundler 1.11.2  remote:        Using rails_serve_static_assets 0.0.5  remote:        Using rails_stdout_logging 0.0.5  remote:        Using tilt 2.0.2  remote:        Using rdoc 4.2.2  remote:        Using tzinfo 1.2.2  remote:        Using nokogiri 1.6.7.2  remote:        Using mime-types 3.0  remote:        Using autoprefixer-rails 6.3.6  remote:        Using uglifier 3.0.0  remote:        Using rack-test 0.6.3  remote:        Using warden 1.2.6  remote:        Using bootstrap-will_paginate 0.0.10  remote:        Using coffee-script 2.4.1  remote:        Using sprockets 3.6.0  remote:        Using elasticsearch-api 1.0.17  remote:        Using faraday 0.9.2  remote:        Using rails_12factor 0.0.3  remote:        Using sdoc 0.4.1  remote:        Using activesupport 4.2.5.1  remote:        Using loofah 2.0.3  remote:        Using mail 2.6.4  remote:        Using rest-client 1.6.7  remote:        Using bootstrap-sass 3.3.6  remote:        Using elasticsearch-transport 1.0.17  remote:        Using rails-deprecated_sanitizer 1.0.3  remote:        Using globalid 0.3.6  remote:        Using activemodel 4.2.5.1  remote:        Using climate_control 0.0.3  remote:        Using jbuilder 2.4.1  remote:        Using rails-html-sanitizer 1.0.3  remote:        Using cloudinary 1.2.0  remote:        Using rails-dom-testing 1.0.7  remote:        Using elasticsearch 1.0.17  remote:        Using activejob 4.2.5.1  remote:        Using cocaine 0.5.8  remote:        Using paperclip-cloudinary 1.1.0  remote:        Using actionview 4.2.5.1  remote:        Using elasticsearch-model 0.1.9  remote:        Using activerecord 4.2.5.1  remote:        Using searchkick 1.2.1  remote:        Using paperclip 4.3.6  remote:        Using actionpack 4.2.5.1  remote:        Using actionmailer 4.2.5.1  remote:        Using railties 4.2.5.1  remote:        Using sprockets-rails 3.0.4  remote:        Using coffee-rails 4.1.1  remote:        Using responders 2.1.2  remote:        Using jquery-rails 4.1.1  remote:        Using rails 4.2.5.1  remote:        Using sass-rails 5.0.4  remote:        Using turbolinks 2.5.3  remote:        Using devise 4.0.0  remote:        Installing sqlite3 1.3.11 with native extensions  remote:          remote:        Gem::Ext::BuildError: ERROR: Failed to build gem native extension.  remote:          remote:        /tmp/build_650c9daea9707f0830f7e2ecbfc558e2/vendor/ruby-2.2.4/bin/ruby -r ./siteconf20160801-197-lz2bsz.rb extconf.rb  remote:        checking for sqlite3.h... no  remote:        sqlite3.h is missing. Try 'port install sqlite3 +universal',  remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'  remote:        and check your shared library search path (the  remote:        location where your sqlite3 shared library is located).  remote:        *** extconf.rb failed ***  remote:        Could not create Makefile due to some reason, probably lack of necessary  remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may  remote:        need configuration options.  remote:          remote:        Provided configuration options:  remote:        --with-opt-dir  remote:        --without-opt-dir  remote:        --with-opt-include  remote:        --without-opt-include=${opt-dir}/include  remote:        --with-opt-lib  remote:        --without-opt-lib=${opt-dir}/lib  remote:        --with-make-prog  remote:        --without-make-prog  remote:        --srcdir=.  remote:        --curdir  remote:        --ruby=/tmp/build_650c9daea9707f0830f7e2ecbfc558e2/vendor/ruby-2.2.4/bin/$(RUBY_BASE_NAME)  remote:        --with-sqlite3-dir  remote:        --without-sqlite3-dir  remote:        --with-sqlite3-include  remote:        --without-sqlite3-include=${sqlite3-dir}/include  remote:        --with-sqlite3-lib  remote:        --without-sqlite3-lib=${sqlite3-dir}/lib  remote:          remote:        extconf failed, exit code 1  remote:          remote:        Gem files will remain installed in /tmp/build_650c9daea9707f0830f7e2ecbfc558e2/vendor/bundle/ruby/2.2.0/gems/sqlite3-1.3.11 for inspection.  remote:        Results logged to /tmp/build_650c9daea9707f0830f7e2ecbfc558e2/vendor/bundle/ruby/2.2.0/extensions/x86_64-linux/2.2.0-static/sqlite3-1.3.11/gem_make.out  remote:        An error occurred while installing sqlite3 (1.3.11), and Bundler cannot  remote:        continue.  remote:        Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling.  remote:  !  remote:  !     Failed to install gems via Bundler.  remote:  !       remote:  !     Detected sqlite3 gem which is not supported on Heroku.  remote:  !     https://devcenter.heroku.com/articles/sqlite3  remote:  !  remote:  !     Push rejected, failed to compile Ruby app.  remote:   remote:  !     Push failed  remote: Verifying deploy...  remote:   remote: !   Push rejected to professor-ratings.  remote:   

Multi timezone task scheduling in Rails (using whenever)

Posted: 01 Aug 2016 05:38 AM PDT

We're currently using 'whenever' to schedule jobs in a Rails project. The system is expanding to support users in multiple timezones (timezone is stored in User model) and we would like to send users an email at a specific time of THEIR day.

Any ideas on the best pattern to achieve this? I'm foreseeing 24 (or more - there are half timezones) 'whenever' tasks per email job each with a different timezone filter on the user table.

Any ideas for a cleaner solution? A better scheduler than whenever perhaps? Something that will create the 24/48 cronjobs and call a callback passing a timezone or a UTC offset? Something like that.

Validate picture upload before create object

Posted: 01 Aug 2016 05:59 AM PDT

So i have a car class which have many photos. And When creating a new car i need to ensure that the user did select a picture first. Here is the implementation.

class Car < ActiveRecord::Base   has_many :photos  end  

and class photo:

class Photo < ActiveRecord::Base  belongs_to :car    has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }  validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/  end  

Here is a part of the car form:

  <%= form_for @car, :html => { multipart: true } do |f| %>                <div class="col-xs-6">                  <div class="form-group">                      <label>Modele</label>                      <%= f.text_field :modele, placeholder: "Modele", class: "form-control" %>                  </div>              </div>                  <div class="row">                  <div class="col-md-4">                      <div class="form-group">                                                      <span class="btn btn-default btn-file">                              <i class="fa fa-cloud-upload fa-lg"></i> Upload Photos                               <%= file_field_tag "images[]", type: :file, multiple: true %>                          </span>                      </div>                        </div>              </div>     <% end %>  

How to fix Cross Site Scripting security warning in rails generated by brakeman?

Posted: 01 Aug 2016 08:04 AM PDT

I used brakeman for generating scanning reports in my application. It generated many Cross Site Scripting security warnings with High Confidence. In that one of them is:

Unescaped parameter value rendered inline near line 47: render(text => "Unexpected EventType #{params["EventType"]}", { :status => 406 }) app/controllers/event_controller.rb. In the controller method shown below, the 1st line is showing the above warning.

I have seen in the link but couldn't fix. Please help. And this is controller code:

  def purchase        render :status => 406, :text => "Unexpected EventType #{params['EventType']}" and return unless params['EventType'] == 'purchased'      @account = Account.new      render :status => 406, :text => "Could not find Plan #{params['Plan']}" and return unless @account.plan = @plan = SubscriptionPlan.find_by_name(params['Plan'])      end  

False Warning for mass assignment is thrown by Brakeman Gem in model.new and model.update_attibutes and model.create

Posted: 01 Aug 2016 07:53 AM PDT

Mass assignment is a feature of Rails which allows an application to create a record from the values of a hash. There are two different mass assignment warnings which can arise. The first is when mass assignment actually occurs. Example:-

User.new(params[:user])  

Although I am not using a hash directly to map with the fields available in the table. Instead I am doing something like:

User.new(:first_name => params[:first_name], :last_name => params[:last_name ], :address => params[:address])  

or

user.update_attributes(:first_name => params[:first_name], :last_name => params[:last_name ], :address => params[:address])  

Why is this leading to a Mass Assignment Vulnerability? As I am not blindly assigning a hash, I am selectively updating only few of the attributes of the table.

One fix for this is by doing the following:

user = User.new  user.first_name = params[:first_name]  user.last_name = params[:last_name ],  user.address = params[:address]  user.save  

But this is like writing unnecessary code, so that the Brakeman is not alerting this as an issue. This is actually doing the same thing in 4 lines instead of a single line.

Can somebody please make me understand what is the actual issue here or confirm that this is a false alert and also is there any way that we can prevent this false alert to appear?

I am using ruby 1.8.7, Rails 2.3.2, Brakeman 3.0.5

Regex for combination of given rules

Posted: 01 Aug 2016 05:30 AM PDT

I'm trying to write regex to validate the password for the given rule.

Passwords must be at least 8 characters in length and contain at least 3 of the following 4 types of characters:

  • lower case letters (i.e. a-z)
  • upper case letters (i.e. A-Z)
  • numbers (i.e. 0-9)
  • special characters (e.g. !@#$&*)

I was going through this discussion and found this really great answer over there.

Now I'm trying to write regex for the mentioned requirements and I came up with the solution like this

^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}|  (?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}|  (?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,}|  (?=.*[A-Z])(?=.*[!@#$&*])(?=.*[a-z]).{8,}|  (?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9]).{8,}$  

and it is working perfect see rubular but I want to optimize these regex and I'm not sure If there are any way to simplify this. Any suggestion will be appreciated. Many thanks

Ruby On Rails - Values not passed on form submit

Posted: 01 Aug 2016 04:58 AM PDT

When the form is submitted all that is in the params hash is the controller and action. None of the form values are present. I have tested and all that is returned is

{"controller"=>"show", "action"=>"create_user"}  

Strict Parameters are being adhered to and the form has the action="post" and I am not using form_for.

VIEW

<div class="image-container set-full-height" style="background-image: url('/assets/img/wizard.jpg'); height: 99%; width: 100%; background-size: cover;">     <!--   Creative Tim Branding   -->     <!--   Big container   -->     <div class="container">        <!-- multistep form -->        <form id="msform" class="form-signin" action="create_user" method="post">           <%= hidden_field_tag :authenticity_token, form_authenticity_token %>           <!-- progressbar -->           <ul id="progressbar">              <li class="active">Login Details</li>              <li>Account Profile</li>              <li>Subscription and Payment</li>           </ul>           <!-- fieldsets -->           <fieldset>              <h2 class="fs-title">Create your account</h2>              <!-- <h3 class="fs-subtitle">Login Credentials</h3> -->              <h4 class="info-text"> Login Credentials</h4>              <%= params.inspect %>              <% if flash[:user_exist_err] %>              <span style="color: red"> <%=flash[:user_exist_err] %></span>              <% end %>              <input type="email" id="username"   placeholder="youremail@somewhere.com" name='username' required="true"/>              <input type="password" id="password" name='password' placeholder="Enter your password." required="true"/>              <input type="button" name="next" class="next action-button" value="Next" />           </fieldset>           <fieldset>              <h2 class="fs-title">Account Profile</h2>              <h3 class="fs-subtitle">Name</h3>              <input type="text" name="f_name" required="true" placeholder="First Name"/>              <input type="text" name="m_name" placeholder="Middle Name or Initial" />              <input type="text" name="l_name" required="true" placeholder="Last Name"/>              <h3 class="fs-subtitle">Address</h3>              <input type="text" name="add" required="true" placeholder="Address 1"/>              <input type="text" name="add2" placeholder="Address 2" />              <input type="text" name="city" required="true" placeholder="city"/>              <input type="text" name="state" required="true" placeholder="State"/>              <input type="text" name="zip" required="true" placeholder="ZipCode"/>              <input type="button" name="previous" class="previous action-button" value="Previous" />              <input type="button" name="next" class="next action-button" value="Next" />           </fieldset>           <fieldset>              <h2 class="fs-title">Payment &amp; Subscription</h2>              <h3 class="fs-subtitle">Choose Your Subscription Type</h3>              <select name="sub_type"require="true" class="form-control">                 <option value="1"  onclick="nopay();">Trial</option>                 <option value="2" onclick="youpay();">Monthly</option>                 <option value="3"  onclick="youpay();">Yearly</option>              </select>              <div id="payment" style="display: none;">                 <h3 class="fs-subtitle">Billing Details</h3>                 <% if flash[:card_info_err] %>                 <span style="color: red"> <%=flash[:card_info_err] %></span>                 <% end %>                 <input id="cardname" type="text" name="noc"  placeholder="Name On Card"/>                 <input id="card_num" type="text" name="card_num" id="first" class="card_num"  placeholder="xxxx" style="width: 23%;"/>-<input id="cc2" type="text" name="card_num[second]" id="second" class="card_num" maxlength="4"  placeholder="xxxx" style="width: 23%;"/>-<input id="cc3" type="text" name="card_num[third]" id="third" class="card_num" maxlength="4"  placeholder="xxxx" style="width: 23%;"/>-<input id="cc4" type="text" name="card_num[fourth]" id="fourth" class="card_num" maxlength="4"  placeholder="xxxx" style="width: 23%;"/>                 <select id="expmonth" name="exp1" class="exp-date form-control"  style="width: 47%; float: left; clear: right;">                    <option selected="selected" disabled>Exp Month</option>                    <%= Date.today.strftime%>                    <option value="01">01</option>                    <option value="02">02</option>                    <option value="03">03</option>                    <option value="04">04</option>                    <option value="05">05</option>                    <option value="06">06</option>                    <option value="07">07</option>                    <option value="08">08</option>                    <option value="09">09</option>                    <option value="10">10</option>                    <option value="11">11</option>                    <option value="12">12</option>                 </select>                 <div  style="width: 6%; float: left; clear: right; margin: -6% auto;">                    <h3>/</h3>                 </div>                 <select class="exp-date form-control" id="expyear" name="exp2"    style="width: 47%; float: left; clear: right;">                    <option selected="selected" disabled de>Exp Year</option>                    <% 15.times.with_index do |i| %>                    <%= "<option value='#{Date.today.year + 1}'>#{Date.today.year + i}</option>".html_safe %>                    <% end %>                 </select>                 <br><br>                 <input type="text" id="cvv" name="cvv" class="cv2" maxlength="3"  placeholder="CV2" style="margin-top: 5%;"/>              </div>              <br>              <input type="button" name="previous" class="previous action-button" value="Previous" />              <input type="submit" name="submit" onclick="this."class="submit action-button" value="Submit" />           </fieldset>        </form>     </div>     <!--  big container -->  </div>  <!-- gigabits code for the form -->  <script>     $(document).ready(function(){       var phone = $('#phone');       $(".card_num").keyup(function()       {         var length = $(this).val().length;           console.log('length');         if (length == 4){           $(this).next('.card_num').focus();         }         });         phone.focusin(function(){         if ($(this).val().length == 0) {           $(this).val('(');         }       });         phone.keyup(function(){         var current = $(this).val();         if (current.length == 4){           $(this).val(current + ') ')         }         else if($(this).val().length == 9)         {           $(this).val(current + '-')         }         })     });      </script>  <script>     //jQuery time     var current_fs, next_fs, previous_fs; //fieldsets     var left, opacity, scale; //fieldset properties which we will animate     var animating; //flag to prevent quick multi-click glitches       $(".next").click(function(){       if(animating) return false;       animating = true;         current_fs = $(this).parent();       next_fs = $(this).parent().next();         //activate next step on progressbar using the index of next_fs       $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");         //show the next fieldset       next_fs.show();       //hide the current fieldset with style       current_fs.animate({opacity: 0}, {         step: function(now, mx) {           //as the opacity of current_fs reduces to 0 - stored in "now"           //1. scale current_fs down to 80%           scale = 1 - (1 - now) * 0.2;           //2. bring next_fs from the right(50%)           left = (now * 50)+"%";           //3. increase opacity of next_fs to 1 as it moves in           opacity = 1 - now;           current_fs.css({             'transform': 'scale('+scale+')',             'position': 'absolute'           });           next_fs.css({'left': left, 'opacity': opacity});         },         duration: 800,         complete: function(){           current_fs.hide();           animating = false;         },         //this comes from the custom easing plugin         easing: 'easeInOutBack'       });     });       $(".previous").click(function(){       if(animating) return false;       animating = true;         current_fs = $(this).parent();       previous_fs = $(this).parent().prev();         //de-activate current step on progressbar       $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");         //show the previous fieldset       previous_fs.show();       //hide the current fieldset with style       current_fs.animate({opacity: 0}, {         step: function(now, mx) {           //as the opacity of current_fs reduces to 0 - stored in "now"           //1. scale previous_fs from 80% to 100%           scale = 0.8 + (1 - now) * 0.2;           //2. take current_fs to the right(50%) - from 0%           left = ((1-now) * 50)+"%";           //3. increase opacity of previous_fs to 1 as it moves in           opacity = 1 - now;           current_fs.css({'left': left});           previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity});         },         duration: 800,         complete: function(){           current_fs.hide();           animating = false;         },         //this comes from the custom easing plugin         easing: 'easeInOutBack'       });     });       $(".submit").click(function(){     document.getElementById('msform').submit();     })  </script>  <script>     function nopay(){      document.getElementById('payment').style.display='none';      document.getElementById('card').required=false;      document.getElementById('cardname').required=false;      document.getElementById('c1').required=false;      document.getElementById('c2').required=false;      document.getElementById('c3').required=false;      document.getElementById('c4').required=false;      document.getElementById('expmonth').required=false;      document.getElementById('expyear').requred=false;      document.getElementById('cv2').required=false;     }     function youpay(){      document.getElementById('payment').style.display='block';      document.getElementById('card').required=true;      document.getElementById('cardname').required=true;      document.getElementById('c1').required=true;      document.getElementById('c2').required=true;      document.getElementById('c3').required=true;      document.getElementById('c4').required=true;      document.getElementById('expmonth').required=true;      document.getElementById('expyear').requred=true;      document.getElementById('cv2').required=true;     }  </script>  

Controller - I am showing only the relevent action for security reasons if more is needed then please ask.

  def create_user  #puts params.inspect  unless UserAccount.where('username = ?', params[:username]).exists?    #using Gibberish::SHA512 to encrypt password      if params[:sub_type] != '1'      response = create_subscription params[:sub_type], params[:f_name], params[:l_name], params[:card_num], params[:exp1], params[:exp2], params[:cvv], params[:email], params[:company], params[:address], params[:city], params[:state], params[:zip] , params[:country]    end    if response != nil || params[:sub_type == '1']      if response.messages.resultCode == MessageTypeEnum::Ok || params[:sub_type] == '1'        puts "Response: #{response.inspect}"        puts "Successfully created a subscription #{response.subscriptionId}"        user = UserAccount.create(:username => params[:username],                                  :password => Gibberish::SHA512("#{params[:password]}"),                                  :first_login => true,                                  :subscription_id => response.subscriptionId,                                  :export_count => 0,                                  :subscription_type_id => params[:sub_type])          contact = Contact.new        contact.user_accounts_id = user.id        contact.f_name = params[:f_name]        contact.m_name = params[:m_name]        contact.l_name = params[:l_name]        contact.address = params[:add]        contact.address2 = params[:add2]        contact.city = params[:city]        contact.state = params[:state]        contact.zip = params[:zip]        contact.save            redirect_to '/show/login'      else        #puts @response.transaction@response.errors.errors[0].errorCode        #puts @response.transaction@response.errors.errors[0].errorText        puts response.messages.messages[0].code        puts response.messages.messages[0].text        flash[:card_info_err] = 'Credit card information is invalid. Please try again.'        redirect_to '/show/signup'      end    end  else    flash[:user_exist_err] = 'That username already exist.'    redirect_to '/show/signup'  end  

end

Select and pluck in rails hitting same SQL query but with different result

Posted: 01 Aug 2016 06:27 AM PDT

I am hitting the following query from my rails console :

Listing.joins(:colors, :sizes, :product, :orders).pluck('colors.id', 'sizes.id', 'products.id', 'orders.id')     (4.5ms)  SELECT colors.id, sizes.id, products.id, orders.id FROM "listings" INNER JOIN "colors" ON "colors"."listing_id" = "listings"."id" INNER JOIN "sizes" ON "sizes"."listing_id" = "listings"."id" INNER JOIN "products" ON "products"."id" = "listings"."product_id" INNER JOIN "orders" ON "orders"."listing_id" = "listings"."id"  

and

Listing.joins(:colors, :sizes, :product, :orders).select('colors.id', 'sizes.id', 'products.id', 'orders.id')    Listing Load (4.6ms)  SELECT colors.id, sizes.id, products.id, orders.id FROM "listings" INNER JOIN "colors" ON "colors"."listing_id" = "listings"."id" INNER JOIN "sizes" ON "sizes"."listing_id" = "listings"."id" INNER JOIN "products" ON "products"."id" = "listings"."product_id" INNER JOIN "orders" ON "orders"."listing_id" = "listings"."id"  

and got the following results respectively :

[[2, 3, 1, 1], [2, 3, 1, 2], [2, 2, 1, 1], [2, 2, 1, 2], [2, 1, 1, 1], [2, 1, 1, 2], [3, 3, 1, 1], [3, 3, 1, 2], [3, 2, 1, 1], [3, 2, 1, 2], [3, 1, 1, 1], [3, 1, 1, 2], [4, 3, 1, 1], [4, 3, 1, 2], [4, 2, 1, 1], [4, 2, 1, 2], [4, 1, 1, 1], [4, 1, 1, 2]]  

and

#<ActiveRecord::Relation [#<Listing id: 1>, #<Listing id: 2>, #<Listing id: 1>, #<Listing id: 2>, #<Listing id: 1>, #<Listing id: 2>, #<Listing id: 1>, #<Listing id: 2>, #<Listing id: 1>, #<Listing id: 2>, ...]>  

Please help this is quiet confusing for me.

I want to deploy my rails app with Mysql as database. I want to go with free heroku server. what are the limitations of this free server?

Posted: 01 Aug 2016 04:16 AM PDT

i have a small rails Application with Mysql database.i want to deploy this application to heroku. but i am not getting the limitations of it. like what is the maximum database size and maximum application size. i know only the ram limitation is upto 512 mb. how many instances it will provides and what is the bandwidth of it etc,like this i want to know all limitations of this free hosting on heroku.

(Object doesn't support #inspect) rails 4.2.0

Posted: 01 Aug 2016 03:50 AM PDT

I am facing (Object doesn't support #inspect) error while fetching the all rows through ActiveRecord .

In my rails Console : LevelFrameworkRule.all where LevelFrameworkRule is model class .

class LevelFrameworkRule < ActiveRecord::Base <br>  end  

I already searched google but could not find the relevant solution to the problem. How can i solve this problem?

Ruby on Rails Geocoder Gem. List results of nearby search returning confusing data

Posted: 01 Aug 2016 06:37 AM PDT

I am trying to build an app with Rails that allows users to search for job listings using geographic locations (addresses to be specific). I'm using the 'geocoder' gem.

gem 'geocoder'

I can successfully search using the rails console using Job.near('sydney',10) and it returns a listing from my database in an array.

2.2.2 :001 > Job.near('sydney', 10 )    Job Load (97.5ms)  SELECT jobs.*, 6371.0 * 2 * ASIN(SQRT(POWER(SIN((-33.8688197 - jobs.latitude) * PI() / 180 / 2), 2) + COS(-33.8688197 * PI() / 180) * COS(jobs.latitude * PI() / 180) * POWER(SIN((151.2092955 - jobs.longitude) * PI() / 180 / 2), 2))) AS distance, MOD(CAST((ATAN2( ((jobs.longitude - 151.2092955) / 57.2957795), ((jobs.latitude - -33.8688197) / 57.2957795)) * 57.2957795) + 360 AS decimal), 360) AS bearing FROM "jobs" WHERE (jobs.latitude BETWEEN -33.958751860591875 AND -33.77888753940813 AND jobs.longitude BETWEEN 151.10098469477293 AND 151.31760630522706 AND (6371.0 * 2 * ASIN(SQRT(POWER(SIN((-33.8688197 - jobs.latitude) * PI() / 180 / 2), 2) + COS(-33.8688197 * PI() / 180) * COS(jobs.latitude * PI() / 180) * POWER(SIN((151.2092955 - jobs.longitude) * PI() / 180 / 2), 2)))) BETWEEN 0.0 AND 10)  ORDER BY distance ASC   => #<ActiveRecord::Relation [#<Job id: 73, title: "Dog walkingn", description: "walk my dog everyday", price: "$25", user_id: "24", timeframe: "daily", created_at: "2016-07-29 05:50:00", updated_at: "2016-07-29 05:50:00", location: nil, job_type_id: "3", street_number: "100", street: "Pitt Street", suburb: "Sydney", state: "NSW", postcode: "2000", country: "Australia", longitude: 151.2092955, latitude: -33.8688197>]>  

But when I do this in controller and try and send the data to the view (jobs.html.erb), all I get is :

#<Job::ActiveRecord_Relation:0x007fd66475abd8>  

here is my controller code:

def location

if params[:location].present?    jobs = Job.near(params[:location],     params[:proximity])      @jobs = jobs  else    @noJobs = 'there is nothing nearby'    @jobs = nil  end  

end

and my view only consists of: (jobs.html.erb)

 <%=  @jobs %>         

can anyone explain to me what is going on and how i can access the data? and what the active record relation actually means?

I'm still pretty new to coding, and this has completely stumped me. I cant find the answer anywhere. Really appreciate any help, Thanks!

Could not install gems on docker container

Posted: 01 Aug 2016 03:41 AM PDT

I'm developing a Rails app using Docker. Now I need to install a new gem, but that does not work.

If I run docker-compose -f dcom-dev.yml run --user $(id -u) web bundle exec gem install youtube_it it gives me such an output:

Fetching: excon-0.51.0.gem (100%)  ERROR:  While executing gem ... (Errno::ENOENT)      No such file or directory @ rb_sysopen - /.gem/ruby/2.3.0/cache/excon-0.51.0.gem  

If I add gem 'youtube_it' to my Gemfile and then run docker-compose -f dcom-dev.yml run --user $(id -u) web bundle exec bundle install it outputs like this:

Could not find gem 'youtube_it' in any of the gem sources listed in your Gemfile or available on this machine.  Run `bundle install` to install missing gems.  

What could be a problem? Thanks in advance!

ActiveRecord::NestedAttributes::TooManyRecords error

Posted: 01 Aug 2016 07:07 AM PDT

In my app, when user register they can upload some files. I need to limit the upload to maximum 5 files. So I have two model with following code

class User < ActiveRecord::Base  has_many :fileuploads, :dependent => :destroy    accepts_nested_attributes_for :fileuploads, limit: 5, :allow_destroy => true      validate do |user|      if user.fileuploads && user.fileuploads.count > 5        errors[:base] << "You can add maximum 5 files."      end    end    end  

and

class Fileupload < ActiveRecord::Base    belongs_to :user  end  

and in my create and update action I added

respond_to do |format|    begin      if @user.save        format.html { redirect_to @user, notice: I18n.t('views.flash_messages.user_was_successfully_created') }      else        format.html { render action: "new" }      end    rescue ActiveRecord::NestedAttributes::TooManyRecords      flash[:error] = 'You can add maximum 5 files. '    end  end  

As you can see from the code above that, I am using limit: 5 and also the validate callback. But both works perfect when I update the user. But when user is created, this error message is not rescued at all. I get this error,

ActiveRecord::NestedAttributes::TooManyRecords in UsersController#create  Maximum 5 records are allowed. Got 7 records instead.  

So why the limit and validate works during user update but not during user creation? And how to make it work for create action as well?

Use Google::Auth::Stores::FileTokenStore with database

Posted: 01 Aug 2016 04:32 AM PDT

I'm trying to implement a 3 legged authentication in my app to the Google API, to be able to access registered users' Google Calendars.

In the quickstart Ruby guide, this command comes up that as far as I understand should point to the user's tokens:

token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)  

It expects the tokens stored in a file (or Redis), but (of course) I store each user's tokens in my database (Postgres).

Have I understand the purpose of the command wrongly or otherwise - how do I use it with a database store?

Official documentation

Rails server jquery datatables pagination

Posted: 01 Aug 2016 03:12 AM PDT

Because of low performance I change all my jquery datatables data to server side (include paging and sorting)

I want to know what the best way to build the query dynamically.

When the query run? In this row carts = Activity.where("sid=33")

Or just when run .each carts.each do |key,val|

This is my code

  def cart_activits_service_search        @site = get_site()        @site_id = @site.idsite        @from_date = params['from'] ? Time.zone.local_to_utc(DateTime.strptime(params['from'], "%Y-%m-%d")) : 6.days.ago.beginning_of_day        @to_date = params['to'] ? Time.zone.local_to_utc(DateTime.strptime(params['to'], "%Y-%m-%d")) : 0.days.ago.to_datetime        limit = 10        limit = params[:iDisplayLength] if params[:iDisplayLength].present?        q = params[:sSearch]        carts = CartActivity.where("idsite = :site_id and server_time between :from_date and :to_date",:site_id => @site.id,:from_date => @from_date, :to_date => @to_date+1.day)        @total_count = carts.count        @sEcho = params[:sEcho]        #where        carts =carts.where(" (email like ?) or (traffic_source like ?) or (event like ?) or (recovery_source like ?) ", "%#{params[:sSearch]}%", "%#{params[:sSearch]}%" , "%#{params[:sSearch]}%", "%#{params[:sSearch]}%") if params[:sSearch].present?          @count = carts.count        carts = carts.order("email")        carts = carts.limit(limit).offset(params[:iDisplayStart])          ret ={}        ret["sEcho"] = @sEcho        ret["iTotalRecords"] = @total_count        ret["iTotalDisplayRecords"] = @count        ret["aaData"] = []          carts.each do |key,val|            @temp =[]            @temp << key.email            @temp << key.server_time            @temp << key.traffic_source            @temp << key.event            @temp << key.recovery_source            @temp << key.cart_total            @temp << key.cart_items            ret["aaData"] << @temp        end          render :json =>  ret             end  

Rails search with 2 select_tag

Posted: 01 Aug 2016 07:02 AM PDT

I'd like to use two select_tags for my search. Actually, it all works fine separately, but I'd like to use choose one option in a first/second tag, then the search begins, and later - choose an option in a second/first tag, and see more detailed search result. For now, I have:

Product model:

class Product < ApplicationRecord    belongs_to :position    has_and_belongs_to_many :size  end  

Size model:

class Size < ApplicationRecord    has_and_belongs_to_many :products    has_many :items  end  

Position model:

class Position < ApplicationRecord    has_many :products  end  

My application.html.erb:

<div class="container">      <div class="row text-center">        <div class="col-sm-6">          <%= form_tag(products_path, method: 'GET', remote: true) do %>            <%= select_tag 'size_id', options_from_collection_for_select(Size.all, 'id', 'title'),                           onchange: ('this.form.submit();'), class: 'form-control', id: 'filter1', include_blank: true %>          <% end %>        </div>        <div class="col-sm-6">          <%= form_tag(products_path, method: 'GET') do %>            <%= select_tag 'position_id', options_from_collection_for_select(Position.all, 'id', 'title'),                           onchange: ('this.form.submit();'), class: 'form-control', id: 'filter2', include_blank: true %>          <% end %>        </div>      </div>    </div>  

And a products_controller:

class ProductsController < ApplicationController    def index          if params[:position_id]        position = Position.find(params[:position_id])        @products = position.products        respond_to do |format|          format.html          format.json { render json: @products }        end      elsif params[:size_id]        size = Size.find(params[:size_id])        @products = size.products        respond_to do |format|          format.html          format.json { render json: @products }        end      else        @products = Product.all        respond_to do |format|          format.html          format.json { render json: @products }        end      end    end  end  

So, how can I do a search that will work not separately? Thanks ahead.

API-only Rails app with 'admin' and 'user' roles best practice

Posted: 01 Aug 2016 03:09 AM PDT

I am rebuilding a standard app in Rails (backend + rendering) and looking into creating API-only Rails backend and Node/React frontent.

I'm a little bit riddled on best practices here.

In my old app I had 2 devise models - User and Admin (admin was a separate namespace, so User would not have access to its controllers).

How would you recommend to implement sets of different controllers for admins and users?

Thanks

No comments:

Post a Comment