Wednesday, November 2, 2016

Why am I getting two different sets of values from my Ruby object when using .to_hash? | Fixed issues

Why am I getting two different sets of values from my Ruby object when using .to_hash? | Fixed issues


Why am I getting two different sets of values from my Ruby object when using .to_hash?

Posted: 02 Nov 2016 07:34 AM PDT

I have an object in my Rails project, and when I do record.to_hash I get values, but I'm missing at least one -- notably experience. When I do record.attributes.to_hash I get more options including the attribute experience. Here's my output from using byebug below. Can anyone explain why this is the case? I was using record.to_hash in conjunction with update_attributes method to update an object but I need the additional attributes.

(byebug) record.to_hash  {:player_url=>"http://www.unlvrebels.com//sports/m-footbl/mtt/casey_acosta_1024286.html", :headshot_url=>nil, :jersey=>"87", :first_name=>"Casey", :last_name=>"Acosta", :position=>"WR", :height=>"5110", :weight=>"160", :eligibility=>nil, :hometown_city=>"Las Vegas", :hometown_state=>"NV", :high_school=>"Chaparral HS", :biography_text=>nil, :is_basketball_player=>false, :possible_dob=>false, :possible_transfer=>false, :possible_redshirt=>false, :possible_gpa=>false, :possible_track_participant=>false, :possible_basketball_participant=>false, :possible_baseball_participant=>false, :possible_hockey_participant=>false, :possible_lacrosse_participant=>false, :possible_power_lifting_participant=>false, :possible_rugby_participant=>false, :possible_soccer_participant=>false, :possible_volleyball_participant=>false, :possible_wrestling_participant=>false, :possible_medical_alert=>false, :possible_character_alert=>false, :school_id=>664, :player_id=>nil, :position_id=>2}  (byebug) record.attributes.to_hash  {"id"=>nil, "school_site_id"=>nil, "player_url"=>"http://www.unlvrebels.com//sports/m-footbl/mtt/casey_acosta_1024286.html", "headshot_url"=>nil, "jersey"=>"87", "first_name"=>"Casey", "last_name"=>"Acosta", "position"=>"WR", "height"=>"5110", "weight"=>"160", "eligibility"=>nil, "hometown_city"=>"Las Vegas", "hometown_state"=>"NV", "high_school"=>"Chaparral HS", "major"=>nil, "previous_school"=>nil, "experience"=>"FR", "biography_text"=>nil, "has_relative_in_sports"=>false, "is_basketball_player"=>false, "possible_dob"=>false, "possible_transfer"=>false, "possible_redshirt"=>false, "possible_gpa"=>false, "possible_track_participant"=>false, "possible_basketball_participant"=>false, "possible_baseball_participant"=>false, "possible_hockey_participant"=>false, "possible_lacrosse_participant"=>false, "possible_power_lifting_participant"=>false, "possible_rugby_participant"=>false, "possible_soccer_participant"=>false, "possible_volleyball_participant"=>false, "possible_wrestling_participant"=>false, "possible_medical_alert"=>false, "possible_character_alert"=>false, "school_id"=>664, "player_id"=>nil, "position_id"=>2, "created_at"=>nil, "updated_at"=>nil}  

How to Show Added Elements Without Refreshing The Page in Rails

Posted: 02 Nov 2016 07:26 AM PDT

I have a form and a div for showing the message which is sent by form. I have to refresh the page after sending a message by form to see the messages in my div. However, I want to see the messages in div without refreshing the page, like a chatroom. I tried to use Ajax but I couldn't make it.

Here is my form:

<%= form_for @message, remote:true do |f| %>    <%= f.text_area :body, class: "form-control", placeholder: "Enter Message" %>  <%= f.submit "Send", class: 'btn btn-primary btn-lg' %>    <% end %>  

And here is my controller

  def new      @message = Message.all    end      def create      @message = Message.new(params.require(:message).permit(:user, :body))      if @message.save        respond_to do |format|          format.js {render :layout => false}          format.html {redirect_to messages_url}        end      else        render 'new'      end    end  

Could anyone help me? Thank you.

Mismatch error on asset loading when accessing heroku hosted rails app from custom domain

Posted: 02 Nov 2016 07:17 AM PDT

The Background

My heroku-hosted rails app allows admins to register a custom domain that their users can use to access a 'white labeled' version of the app. The 'white labeled' domains point at dogmessenger.com (I'm using a fake url/info because this is a production app) and are registered with heroku, and the application serves the same functionality just with different paths, like so:

Normal urls:

dogmessenger.com/breeds/labrador/puppies

"White labeled" urls:

dogs.welovelabs.com/puppies

The Issue

This has worked just fine for about 6 months, but I've suddenly begun getting errors when accessing the app from white labeled urls. The server will quickly respond with a 200 OK, rendering all the partials and completing all the logic with no errors in the logs. However, client-side, the loading icon will spin for ~1.5 minutes, then finally load the page without any styling, with errors in the javascript console like this:

http://dogs.welovelabs.com/assets/application-bc31329678384dfd747df7fa2b8e77f2.css Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

The app continues to function properly, allowing users to use the app, as long as they dont mind waiting 1.5 minutes between each click, and not seeing any styling. What's weirder, is that sometimes it works normally! For example, right now it's working just fine in chrome on my mac, but giving me a timeout error on my iPhone. Sometimes the opposite occurs.

The 'Band-Aid' Solution

I posted on r/rails asking for help and u/SminkyBazzA suggested running

heroku run rake tmp:clear   heroku run rake assets:clean  heroku restart  heroku run rake assets:precompile   

This seems to solve the issue, and all devices/browsers that I access the app work just fine. However, as soon as I push another update to production, the issue returns until I run this code again. Any ideas on what is causing this problem and how I can fix it permanently?

Sign in function on a webpage not working (Ruby on Rails)

Posted: 02 Nov 2016 07:43 AM PDT

Why does my webpage display an "Invalid email/password combination" error regardless if the email/password combination is correct or not? I'm new to ruby on rails and maybe someone with a better understanding of ruby might be able to point me in right direction. I'll post the relevant code below. Basically a candidate will sign into the page with an email (can_email) and password.

class SessionsController < ApplicationController    def new  end    def create  candidate = Candidate.find_by_can_email(params[:can_email])  if candidate && candidate.authenticate(params[:password])              session[:candidate_id] = candidate.id              redirect_to candidate  else      flash.now[:error]="Invalid email/password combination"      render 'new'      end   end     def destroy   if signed_in?          session[:candidate_id] = nil   else           flash[:notice] = "You need to log in first"   end    redirect_to login_path   end  end        module ApplicationHelper    def signed_in?          if session[:candidate_id].nil?            return          else            @current_candidate = Candidate.find_by_id(session[:candidate_id])       end    end  end  

Streaming CSV with Rails 4.2 - empty file?

Posted: 02 Nov 2016 07:09 AM PDT

I'm returning a lot of data and thus want to stream CSV with rails 4.2: https://gist.github.com/solars/273512ae56397a445632687001b109aa

According to what I saw this should work, but apparently I only get an empty file with no rows.

The query is working. I think I have to use the Enumerator in a different way but didn't find too much on this topic, can anyone please help?

Thank you!

Saving sub object (via has_many) in create method rails

Posted: 02 Nov 2016 07:05 AM PDT

I've been trying to save sub-objects in a controller on my rails API.

My API is to create and organize congresses data.

One congres has one or many hotels, and hotels can have one or many hotel_various_infos.

The JSON I'm sending through POST /congresses is as following :

{    "name": "Congress' name",    "subtitle": "",    "place": "cologne, germany",    "date_from": "2016-10-22T00:00:00.000Z",    "date_to": "2016-10-25T00:00:00.000Z",    "host_company": "Hosting company",    "host_logo_url": "http://www.path.com/what/ever.jpg",    "color" : "#121212",    "template_id" : "1",    "hotels": [      {        "name": "radisson blue Cologne",        "address": "Messe Kreisel 3",        "postal_code": "DE-50679",        "city": "Cologne",        "country": "Germany",        "phone_nbr": "+49221277200",        "check_in_time": "15:00",        "check_out_time": "12:00",        "hotel_various_infos": [          {              "title": "Welcome Desk",              "content": "Should you require any assistance during your stay, a *** welcome desk will be open each day in the hotel lobby."          }        ]      }    ]  }  

Here you can find my models :

congres.rb

class Congress < ApplicationRecord    has_many :hotels, autosave: true    has_many :agenda_events, autosave: true  end  

hotel.rb

class Hotel < ApplicationRecord    belongs_to :congress    has_many :hotel_various_infos, autosave: true  end  

hotel_various_info.rb

class HotelVariousInfo < ApplicationRecord belongs_to :hotels end

And this is my congresses' controller :

  # POST /congresses    def create      @congress = Congress.new(congress_params)      hotels_params.each do |hotel_param|        @congress.hotels.new(hotel_param)        p '>>'        p hotel_info_params        p '<<'        hotel_info_params.each do |hotel_info_param|          @congress.hotels.hotel_various_infos.new(hotel_info_param)        end      end          if @congress.save        render json: @congress, status: :created, location: @congress      else        render json: @congress.errors, status: :unprocessable_entity      end    end        # Only allow a trusted parameter "white list" through.    def congress_params      params.require(:congress).permit(          :name,          :subtitle,          :place,          :date_from,          :date_to,          :host_company,          :host_logo_url,          :color,          :template_id,          :hotels,          :hotel_various_infos      )    end      def hotels_params      params.permit(          hotels: [:name,                   :address,                   :postal_code,                   :city, :country,                   :phone_nbr,                   :check_in_time,                   :check_out_time          ]      ).require(:hotels)    end      def hotel_info_params      params.permit(hotel_various_infos: [:title, :content]).require(:hotel_various_infos)    end  

I'm not sure about my usage of strong parameters.

I get a "exception": "#", when calling this route.

Congres and its hotel are perfectly handled when "hotel_various_info" handling is removed.

When I call /congresses/{ID} I get the congres, hotels, and hotel_various_informations without any problem.

Thanks for your help.

Why is my app trying to load bourbon?

Posted: 02 Nov 2016 07:17 AM PDT

I'm having a weird gem problem here. Since the last time I ran bundle install, my app crashes spectacularily with this nice error message: Sass::SyntaxError File to import not found or unreadable: bourbon.

I don't get it, since I'm NOT using bourbon! It's not in the gemfile, and not in the generated gemfile.lock I can't find why my app tries to load it now, but it does so at the first image it finds in the views.

I've tried to run gem pristine --all, with no success.

Here's my gemfile:

source 'https://rubygems.org'    gem 'rake', '11.3.0'    #LogLinkedIn   #gem 'omniauth-linkedin-oauth2'  #TimeDiff  gem 'time_difference'  #LogFacebook  gem 'omniauth-facebook'  #LogTwitter  gem 'omniauth-twitter'  #LogGoogle  gem "omniauth-google-oauth2"  gem 'omniauth'  # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.5.1'  # Use sqlite3 as the database for Active Record  #gem 'sqlite3'  gem "haml-rails", "~> 0.9"  gem 'chosen-rails'  # 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'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby  # Use jquery as the JavaScript library  gem 'jquery-rails'  gem "jquery-ui-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    gem 'devise', '3.4.1'  #bootstrap-sass is not relevant to the tutorial, but I like it for styling.  gem 'bootstrap-sass'  gem 'font-awesome-sass'    gem 'jquery-turbolinks'  # droits d'accès  gem "cancan"  gem 'minitest'  # gem 'paper_trail'  # traductions  gem 'globalize', '~> 5.0.0'  gem 'rails-i18n'  # for avatars  gem "paperclip", "~> 4.3"  # for datum validations  gem 'validates_timeliness', '~> 4.0'  # crop image  gem 'jcrop-rails-v2'  # datepicker calendar  gem 'bootstrap-datepicker-rails'  #interface admin  gem "administrate", "~> 0.1.4"    # autocomplete search  gem 'rails-jquery-autocomplete'  # seed dump  gem 'seed_dump'    #gems for async actions  gem 'private_pub'  gem 'thin'    gem 'sunspot_solr'  gem 'sunspot_rails'    # pagination  gem 'kaminari'  #text editor  gem 'ckeditor_rails'  # wizardify models  gem 'wicked'  gem 'unread'  # mangopay!  gem 'mangopay'  gem 'countries'  gem 'progress_bar'  # conversations & messages  gem 'mailboxer'  # cron jobs  gem 'whenever', :require => false    # validate card number  gem 'jquery-form-validator-rails'      # datetimepicker  gem 'momentjs-rails', '~> 2.10.6'  gem 'bootstrap3-datetimepicker-rails', '~> 4.17.37'    gem 'fullcalendar-rails'    #Sans la Gem Erreur concernant les Images_Tags  gem 'coffee-script-source', '1.8.0'      # Use ActiveModel has_secure_password  # gem 'bcrypt', '~> 3.1.7'    gem 'bigbluebutton_rails', github: 'mconf/bigbluebutton_rails'        gem 'resque', :require => "resque/server"    gem 'devise_lastseenable'    gem "factory_girl_rails", "~> 4.0"    gem 'capybara' #Pour les test    gem "rails-erd"    gem 'active_interaction'  gem 'hashie'  gem 'pluck_to_hash'  gem 'drafting'  gem 'ruby-duration'    # Use Unicorn as the app server  # gem 'unicorn'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development    group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    #gem 'byebug'    gem 'sqlite3', '1.3.11'    gem 'byebug',      '3.4.0'    gem 'ffaker'    gem 'webmock'    gem 'vcr'    gem 'rspec-rails', '~> 3.0'      # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'    end    group :test do    gem 'capybara-screenshot'    gem 'sunspot-rails-tester'  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> in views    gem 'web-console', '~> 2.0'  end    group :production do    gem 'pg',             '0.17.1'    gem 'rails_12factor', '0.0.2'  end  

And gemfile.lock

GIT    remote: git://github.com/mconf/bigbluebutton_rails.git    revision: 46ef87d87ec2f3dd14fa843f3dcbbc63ebdafe5b    specs:      bigbluebutton_rails (2.1.0)        bigbluebutton-api-ruby (~> 1.6)        browser (~> 0.8.0)        rails (>= 4.0.0)        resque (~> 1.25.1)        resque-scheduler (~> 3.0)    GEM    remote: https://rubygems.org/    specs:      actionmailer (4.2.5.1)        actionpack (= 4.2.5.1)        actionview (= 4.2.5.1)        activejob (= 4.2.5.1)        mail (~> 2.5, >= 2.5.4)        rails-dom-testing (~> 1.0, >= 1.0.5)      actionpack (4.2.5.1)        actionview (= 4.2.5.1)        activesupport (= 4.2.5.1)        rack (~> 1.6)        rack-test (~> 0.6.2)        rails-dom-testing (~> 1.0, >= 1.0.5)        rails-html-sanitizer (~> 1.0, >= 1.0.2)      actionview (4.2.5.1)        activesupport (= 4.2.5.1)        builder (~> 3.1)        erubis (~> 2.7.0)        rails-dom-testing (~> 1.0, >= 1.0.5)        rails-html-sanitizer (~> 1.0, >= 1.0.2)      active_interaction (3.4.0)        activemodel (>= 4, < 6)      activejob (4.2.5.1)        activesupport (= 4.2.5.1)        globalid (>= 0.3.0)      activemodel (4.2.5.1)        activesupport (= 4.2.5.1)        builder (~> 3.1)      activerecord (4.2.5.1)        activemodel (= 4.2.5.1)        activesupport (= 4.2.5.1)        arel (~> 6.0)      activesupport (4.2.5.1)        i18n (~> 0.7)        json (~> 1.7, >= 1.7.7)        minitest (~> 5.1)        thread_safe (~> 0.3, >= 0.3.4)        tzinfo (~> 1.1)      addressable (2.4.0)      administrate (0.1.5)        autoprefixer-rails (~> 6.0)        datetime_picker_rails (~> 0.0.7)        jquery-rails (~> 4.0)        kaminari (~> 0.16)        momentjs-rails (~> 2.8)        neat (~> 1.1)        normalize-rails (~> 3.0)        rails (~> 4.2)        sass-rails (~> 5.0)        selectize-rails (~> 0.6)      arel (6.0.3)      autoprefixer-rails (6.5.1.1)        execjs      bcrypt (3.1.11)      bigbluebutton-api-ruby (1.6.0)        xml-simple (~> 1.1)      binding_of_caller (0.7.2)        debug_inspector (>= 0.0.1)      bootstrap-datepicker-rails (1.6.4.1)        railties (>= 3.0)      bootstrap-sass (3.3.7)        autoprefixer-rails (>= 5.2.1)        sass (>= 3.3.4)      bootstrap3-datetimepicker-rails (4.17.42)        momentjs-rails (>= 2.8.1)      browser (0.8.0)      builder (3.2.2)      byebug (3.4.0)        columnize (~> 0.8)        debugger-linecache (~> 1.2)        slop (~> 3.6)      cancan (1.6.10)      capybara (2.10.1)        addressable        mime-types (>= 1.16)        nokogiri (>= 1.3.3)        rack (>= 1.0.0)        rack-test (>= 0.5.4)        xpath (~> 2.0)      capybara-screenshot (1.0.14)        capybara (>= 1.0, < 3)        launchy      carrierwave (0.11.2)        activemodel (>= 3.2.0)        activesupport (>= 3.2.0)        json (>= 1.7)        mime-types (>= 1.16)        mimemagic (>= 0.3.0)      choice (0.2.0)      chosen-rails (1.5.2)        coffee-rails (>= 3.2)        railties (>= 3.0)        sass-rails (>= 3.2)      chronic (0.10.2)      ckeditor_rails (4.5.10)        railties (>= 3.0)      climate_control (0.0.3)        activesupport (>= 3.0)      cocaine (0.5.8)        climate_control (>= 0.0.3, < 1.0)      coffee-rails (4.1.1)        coffee-script (>= 2.2.0)        railties (>= 4.0.0, < 5.1.x)      coffee-script (2.4.1)        coffee-script-source        execjs      coffee-script-source (1.8.0)      columnize (0.9.0)      concurrent-ruby (1.0.2)      cookiejar (0.3.3)      countries (1.2.5)        currencies (~> 0.4.2)        i18n_data (~> 0.7.0)      crack (0.4.3)        safe_yaml (~> 1.0.0)      currencies (0.4.2)      daemons (1.2.4)      datetime_picker_rails (0.0.7)        momentjs-rails (>= 2.8.1)      debug_inspector (0.0.2)      debugger-linecache (1.2.0)      devise (3.4.1)        bcrypt (~> 3.0)        orm_adapter (~> 0.1)        railties (>= 3.2.6, < 5)        responders        thread_safe (~> 0.1)        warden (~> 1.2.3)      devise_lastseenable (0.0.6)        devise        rails (>= 3.0.4)      diff-lcs (1.2.5)      drafting (0.3.0)        activerecord (>= 4.1)      em-http-request (1.1.5)        addressable (>= 2.3.4)        cookiejar (!= 0.3.1)        em-socksify (>= 0.3)        eventmachine (>= 1.0.3)        http_parser.rb (>= 0.6.0)      em-socksify (0.3.1)        eventmachine (>= 1.0.0.beta.4)      erubis (2.7.0)      eventmachine (1.2.0.1)      execjs (2.7.0)      factory_girl (4.7.0)        activesupport (>= 3.0.0)      factory_girl_rails (4.7.0)        factory_girl (~> 4.7.0)        railties (>= 3.0.0)      faraday (0.9.2)        multipart-post (>= 1.2, < 3)      faye (1.2.3)        cookiejar (>= 0.3.0)        em-http-request (>= 0.3.0)        eventmachine (>= 0.12.0)        faye-websocket (>= 0.9.1)        multi_json (>= 1.0.0)        rack (>= 1.0.0)        websocket-driver (>= 0.5.1)      faye-websocket (0.10.4)        eventmachine (>= 0.12.0)        websocket-driver (>= 0.5.1)      ffaker (2.2.0)      font-awesome-sass (4.7.0)        sass (>= 3.2)      fullcalendar-rails (3.0.0.0)        jquery-rails (>= 4.0.5, < 5.0.0)        jquery-ui-rails (>= 5.0.2)        momentjs-rails (>= 2.9.0)      globalid (0.3.7)        activesupport (>= 4.1.0)      globalize (5.0.1)        activemodel (>= 4.2.0, < 4.3)        activerecord (>= 4.2.0, < 4.3)      haml (4.0.7)        tilt      haml-rails (0.9.0)        actionpack (>= 4.0.1)        activesupport (>= 4.0.1)        haml (>= 4.0.6, < 5.0)        html2haml (>= 1.0.1)        railties (>= 4.0.1)      hashdiff (0.3.0)      hashie (3.4.6)      highline (1.7.8)      html2haml (2.0.0)        erubis (~> 2.7.0)        haml (~> 4.0.0)        nokogiri (~> 1.6.0)        ruby_parser (~> 3.5)      http_parser.rb (0.6.0)      i18n (0.7.0)      i18n_data (0.7.0)      iso8601 (0.9.1)      jbuilder (2.6.0)        activesupport (>= 3.0.0, < 5.1)        multi_json (~> 1.2)      jcrop-rails-v2 (0.9.12.3)      jquery-form-validator-rails (0.0.2)        railties (>= 3.2, < 5.0)        thor (~> 0.14)      jquery-rails (4.2.1)        rails-dom-testing (>= 1, < 3)        railties (>= 4.2.0)        thor (>= 0.14, < 2.0)      jquery-turbolinks (2.1.0)        railties (>= 3.1.0)        turbolinks      jquery-ui-rails (5.0.5)        railties (>= 3.2.16)      json (1.8.3)      jwt (1.5.6)      kaminari (0.17.0)        actionpack (>= 3.0.0)        activesupport (>= 3.0.0)      launchy (2.4.3)        addressable (~> 2.3)      loofah (2.0.3)        nokogiri (>= 1.5.9)      mail (2.6.4)        mime-types (>= 1.16, < 4)      mailboxer (0.14.0)        carrierwave (>= 0.5.8)        rails (>= 4.2.0)      mangopay (3.0.25)        multi_json (>= 1.7.7)      mime-types (3.1)        mime-types-data (~> 3.2015)      mime-types-data (3.2016.0521)      mimemagic (0.3.0)      mini_portile2 (2.1.0)      minitest (5.9.1)      momentjs-rails (2.10.6)        railties (>= 3.1)      mono_logger (1.1.0)      multi_json (1.12.1)      multi_xml (0.5.5)      multipart-post (2.0.0)      neat (1.8.0)        sass (>= 3.3)        thor (~> 0.19)      nokogiri (1.6.8.1)        mini_portile2 (~> 2.1.0)      normalize-rails (3.0.3)      oauth (0.5.1)      oauth2 (1.2.0)        faraday (>= 0.8, < 0.10)        jwt (~> 1.0)        multi_json (~> 1.3)        multi_xml (~> 0.5)        rack (>= 1.2, < 3)      omniauth (1.3.1)        hashie (>= 1.2, < 4)        rack (>= 1.0, < 3)      omniauth-facebook (4.0.0)        omniauth-oauth2 (~> 1.2)      omniauth-google-oauth2 (0.4.1)        jwt (~> 1.5.2)        multi_json (~> 1.3)        omniauth (>= 1.1.1)        omniauth-oauth2 (>= 1.3.1)      omniauth-oauth (1.1.0)        oauth        omniauth (~> 1.0)      omniauth-oauth2 (1.4.0)        oauth2 (~> 1.0)        omniauth (~> 1.2)      omniauth-twitter (1.2.1)        json (~> 1.3)        omniauth-oauth (~> 1.1)      options (2.3.2)      orm_adapter (0.5.0)      paperclip (4.3.7)        activemodel (>= 3.2.0)        activesupport (>= 3.2.0)        cocaine (~> 0.5.5)        mime-types        mimemagic (= 0.3.0)      pg (0.17.1)      pluck_to_hash (1.0.0)        activerecord (>= 4.0.2)        activesupport (>= 4.0.2)      pr_geohash (1.0.0)      private_pub (1.0.3)        faye      progress_bar (1.0.5)        highline (~> 1.6)        options (~> 2.3.0)      rack (1.6.4)      rack-protection (1.5.3)        rack      rack-test (0.6.3)        rack (>= 1.0)      rails (4.2.5.1)        actionmailer (= 4.2.5.1)        actionpack (= 4.2.5.1)        actionview (= 4.2.5.1)        activejob (= 4.2.5.1)        activemodel (= 4.2.5.1)        activerecord (= 4.2.5.1)        activesupport (= 4.2.5.1)        bundler (>= 1.3.0, < 2.0)        railties (= 4.2.5.1)        sprockets-rails      rails-deprecated_sanitizer (1.0.3)        activesupport (>= 4.2.0.alpha)      rails-dom-testing (1.0.7)        activesupport (>= 4.2.0.beta, < 5.0)        nokogiri (~> 1.6.0)        rails-deprecated_sanitizer (>= 1.0.1)      rails-erd (1.5.0)        activerecord (>= 3.2)        activesupport (>= 3.2)        choice (~> 0.2.0)        ruby-graphviz (~> 1.2)      rails-html-sanitizer (1.0.3)        loofah (~> 2.0)      rails-i18n (4.0.9)        i18n (~> 0.7)        railties (~> 4.0)      rails-jquery-autocomplete (1.0.3)        rails (>= 3.2)      rails_12factor (0.0.2)        rails_serve_static_assets        rails_stdout_logging      rails_serve_static_assets (0.0.5)      rails_stdout_logging (0.0.5)      railties (4.2.5.1)        actionpack (= 4.2.5.1)        activesupport (= 4.2.5.1)        rake (>= 0.8.7)        thor (>= 0.18.1, < 2.0)      rake (11.3.0)      rdoc (4.2.2)        json (~> 1.4)      redis (3.3.1)      redis-namespace (1.5.2)        redis (~> 3.0, >= 3.0.4)      responders (2.3.0)        railties (>= 4.2.0, < 5.1)      resque (1.25.2)        mono_logger (~> 1.0)        multi_json (~> 1.0)        redis-namespace (~> 1.3)        sinatra (>= 0.9.2)        vegas (~> 0.1.2)      resque-scheduler (3.1.0)        mono_logger (~> 1.0)        redis (~> 3.0)        resque (~> 1.25)        rufus-scheduler (~> 2.0)      rsolr (1.1.2)        builder (>= 2.1.2)      rspec-core (3.5.4)        rspec-support (~> 3.5.0)      rspec-expectations (3.5.0)        diff-lcs (>= 1.2.0, < 2.0)        rspec-support (~> 3.5.0)      rspec-mocks (3.5.0)        diff-lcs (>= 1.2.0, < 2.0)        rspec-support (~> 3.5.0)      rspec-rails (3.5.2)        actionpack (>= 3.0)        activesupport (>= 3.0)        railties (>= 3.0)        rspec-core (~> 3.5.0)        rspec-expectations (~> 3.5.0)        rspec-mocks (~> 3.5.0)        rspec-support (~> 3.5.0)      rspec-support (3.5.0)      ruby-duration (3.2.3)        activesupport (>= 3.0.0)        i18n        iso8601      ruby-graphviz (1.2.2)      ruby_parser (3.8.3)        sexp_processor (~> 4.1)      rufus-scheduler (2.0.24)        tzinfo (>= 0.3.22)      safe_yaml (1.0.4)      sass (3.4.22)      sass-rails (5.0.6)        railties (>= 4.0.0, < 6)        sass (~> 3.1)        sprockets (>= 2.8, < 4.0)        sprockets-rails (>= 2.0, < 4.0)        tilt (>= 1.1, < 3)      sdoc (0.4.2)        json (~> 1.7, >= 1.7.7)        rdoc (~> 4.0)      seed_dump (3.2.4)        activerecord (>= 4)        activesupport (>= 4)      selectize-rails (0.12.3)      sexp_processor (4.7.0)      sinatra (1.4.7)        rack (~> 1.5)        rack-protection (~> 1.4)        tilt (>= 1.3, < 3)      slop (3.6.0)      spring (2.0.0)        activesupport (>= 4.2)      sprockets (3.7.0)        concurrent-ruby (~> 1.0)        rack (> 1, < 3)      sprockets-rails (3.2.0)        actionpack (>= 4.0)        activesupport (>= 4.0)        sprockets (>= 3.0.0)      sqlite3 (1.3.11)      sunspot (2.2.7)        pr_geohash (~> 1.0)        rsolr (>= 1.1.1, < 3)      sunspot-rails-tester (1.0.0)        sunspot_rails (>= 1.2)        sunspot_solr (>= 1.2)      sunspot_rails (2.2.7)        nokogiri        rails (>= 3)        sunspot (= 2.2.7)      sunspot_solr (2.2.7)      thin (1.7.0)        daemons (~> 1.0, >= 1.0.9)        eventmachine (~> 1.0, >= 1.0.4)        rack (>= 1, < 3)      thor (0.19.1)      thread_safe (0.3.5)      tilt (2.0.5)      time_difference (0.5.0)        activesupport      timeliness (0.3.8)      turbolinks (5.0.1)        turbolinks-source (~> 5)      turbolinks-source (5.0.0)      tzinfo (1.2.2)        thread_safe (~> 0.1)      uglifier (3.0.3)        execjs (>= 0.3.0, < 3)      unread (0.8.2)        activerecord (>= 3)      validates_timeliness (4.0.2)        timeliness (~> 0.3.7)      vcr (3.0.3)      vegas (0.1.11)        rack (>= 1.0.0)      warden (1.2.6)        rack (>= 1.0)      web-console (2.3.0)        activemodel (>= 4.0)        binding_of_caller (>= 0.7.2)        railties (>= 4.0)        sprockets-rails (>= 2.0, < 4.0)      webmock (2.1.0)        addressable (>= 2.3.6)        crack (>= 0.3.2)        hashdiff      websocket-driver (0.6.4)        websocket-extensions (>= 0.1.0)      websocket-extensions (0.1.2)      whenever (0.9.7)        chronic (>= 0.6.3)      wicked (1.3.1)        railties (>= 3.0.7)      xml-simple (1.1.5)      xpath (2.0.0)        nokogiri (~> 1.3)    PLATFORMS    ruby    DEPENDENCIES    active_interaction    administrate (~> 0.1.4)    bigbluebutton_rails!    bootstrap-datepicker-rails    bootstrap-sass    bootstrap3-datetimepicker-rails (~> 4.17.37)    byebug (= 3.4.0)    cancan    capybara    capybara-screenshot    chosen-rails    ckeditor_rails    coffee-rails (~> 4.1.0)    coffee-script-source (= 1.8.0)    countries    devise (= 3.4.1)    devise_lastseenable    drafting    factory_girl_rails (~> 4.0)    ffaker    font-awesome-sass    fullcalendar-rails    globalize (~> 5.0.0)    haml-rails (~> 0.9)    hashie    jbuilder (~> 2.0)    jcrop-rails-v2    jquery-form-validator-rails    jquery-rails    jquery-turbolinks    jquery-ui-rails    kaminari    mailboxer    mangopay    minitest    momentjs-rails (~> 2.10.6)    omniauth    omniauth-facebook    omniauth-google-oauth2    omniauth-twitter    paperclip (~> 4.3)    pg (= 0.17.1)    pluck_to_hash    private_pub    progress_bar    rails (= 4.2.5.1)    rails-erd    rails-i18n    rails-jquery-autocomplete    rails_12factor (= 0.0.2)    rake (= 11.3.0)    resque    rspec-rails (~> 3.0)    ruby-duration    sass-rails (~> 5.0)    sdoc (~> 0.4.0)    seed_dump    spring    sqlite3 (= 1.3.11)    sunspot-rails-tester    sunspot_rails    sunspot_solr    thin    time_difference    turbolinks    uglifier (>= 1.3.0)    unread    validates_timeliness (~> 4.0)    vcr    web-console (~> 2.0)    webmock    whenever    wicked    BUNDLED WITH     1.13.6  

Any insight would be appreciated!

Rails get Model :id via Post

Posted: 02 Nov 2016 06:52 AM PDT

I am looking for a way to access a model via its :id.

My project looks like this:

First someone can register himself in a form. Then he gets forwarded to a page where he can edit the things he entered. Now I do not want that you can see something in the URL.

Rails Devise methods & helpers don't work

Posted: 02 Nov 2016 06:51 AM PDT

I have inherited an application built with Rails (v. 4.2.0) + AngularJS. Most of it works reasonably well, but I have hit a wall with Devise (v .3.5.1) that I am unable to overcome.

The application is structured this way: Angular.js handles the client side and is served from the back by the Rails app through an API. (The structure is very similar to the one from this tutorial: https://thinkster.io/angular-rails).

The problem if that for some reason, the app does not recognize helper methods of devise such as: current_user or user_signin? among others. Currently, anyone could make a request to /api/users and get a JSON with the information.

For instance, if we add this code to the /controllers/api/employees_controller.rb and you make a request in your browser to /api/employees/:id you get the JSON despite nos being logged

def show    @employee = Employee.find(params[:id])    respond_to do |format|      format.json{        if user_signed_in? then          render text: @employee.to_json, status: 200        else          render :json => nil, status: 422        end      }    end  end  

Note: in this application the entity "Employee" is a type of "User"

I have tried solutions named in this post Rails devise: user_signed_in? not working but it didn't work for me

Here are all the parts of the code that I think could offer some light to this issue

/controllers/api/users/sessions_controller.rb

module Api    class Users::SessionsController < Devise::SessionsController    before_filter :configure_sign_in_params, only: [:create]        #Devise couldn't find "users_url" so just defining it here (500 error)      def users_url        :root_path      end        # GET /resource/sign_in      def new        super      end        # POST /resource/sign_in      def create        user = User.new        if ( params[:user][:email] == "" || params[:user][:password] == "") then      render json: {errors: "Insufficient data provided (user and/or password)"}.to_json, status: :bad_request        elsif User.find_by_email(params[:user][:email]).present?      user = User.find_by_email(params[:user][:email])      if user.valid_password?(params[:user][:password]) then        sign_in :user, user        render json: user.to_json(only: [:id, :email, :name, :last_name, :type, :company_id,:configuration,:phone]), status: :created      else        render json: {errors: "Wrong password."}.to_json, status: :unauthorized      end        else      render json: {errors: "Could not find user with that email."}.to_json, status: :unauthorized        end      end        # DELETE /resource/sign_out      def destroy        puts "HEEEEY"      end        # protected        # If you have extra params to permit, append them to the sanitizer.      def configure_sign_in_params        devise_parameter_sanitizer.for(:sign_in) << :attribute      end    end  end  

models/user.rb

class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable#, :confirmable      scope :admins, -> { where(admin: true) }      validates :email, presence: true    validates :name, presence: true, length: { in: 1..50 }    end  

config/routes.rb

Rails.application.routes.draw do     namespace :api, defaults: {format: :json} do       resources :contacts     resources :job_application    #  devise_for :admins, controllers: {sessions: 'admins/sessions'}    #  devise_for :employees, controllers: {sessions: 'employees/sessions'}        devise_for :users, controllers: {      sessions: 'api/users/sessions',      registrations: 'api/users/registrations',      }        devise_for :employees, controllers: {         sessions: 'api/employees/sessions',         registrations: 'api/employees/registrations',       }  

If you need any other part of the code, please just let me know.

Thank you very much!

Rails Send Email when a Specified Field is Updated

Posted: 02 Nov 2016 07:30 AM PDT

I have an app that is used for tracking in house devices. Once a device has been through the system it ships, so I am updating the 'Ticket'. I've been through a lot of contact form tutorials but they don't really help because they are all based on either gems or create methods.

The code below mostly works but with two glaring problems: The @ticket.tracking is not passing in tracking to appear in the email and it is trying to find the linked template when it should just perform the action then redirect back to the edit page.

Form:

<%= form_for(@ticket, url: send_tracking_mail_path(@ticket)) do |tickettracking| %>    <%= tickettracking.text_field :tracking %>    <%= tickettracking.submit 'Submit Tracking', class: "btn btn-primary btn-mini", style: "float: right;" %>  <% end %>  

Ticket Controller:

def send_tracking_mail   @ticket = Ticket.find(params[:id])   TrackingMailer.tracking(@ticket).deliver_now   flash[:notice] = "Ticket tracking has been sent."  end  

Tracking Mailer:

class TrackingMailer < ApplicationMailer   def tracking(ticket)    @ticket = ticket    mail(to: @ticket.customer.email, subject: "Tracking for #{ticket.name}")   end  end  

The route:

patch 'send_tracking_mail.:id', to: 'tickets#send_tracking_mail', as: :send_tracking_mail  

The email sends but renders nothing for <%= @ticket.tracking %>

Your Device Has Been Shipped with tracking <%= @ticket.tracking %>  

Edit: I was missing a couple of lines in the email method

def send_tracking_mail   @ticket = Ticket.find(params[:id])   @ticket.update(ticket_params)   TrackingMailer.tracking(@ticket).deliver_now   redirect_to edit_ticket_path(@ticket)  end  

Passing URI as parameter in Rails, which encoding is better?

Posted: 02 Nov 2016 06:35 AM PDT

I'm working on an API made in Rails 4.2. Thing is, the data handled by the API is not identified by ID, but by URI. So my path for the find action is

http://.../api/v2/taxons/:uri  

An example of the URI I need to pass as parameter is http://www.ebusiness-unibw.org/ontologies/pcs2owl/gpc/C_10001334-tax.html, so my GET would be

http://.../api/v2/taxons/http://www.ebusiness-unibw.org/ontologies/pcs2owl/gpc/C_10001334-tax.html  

Of course it doesn't work like that, so I need to encode it. Should I use CGI.escape or Base64.urlsafe_encode64? Why?

Nginx + Passenger + Rails HTTP 499 in Logs after long running

Posted: 02 Nov 2016 06:34 AM PDT

I am having an issue with my NGINX+Passenger+Rails setup. One requests takes forever to run and is not canceled. I am not sure what is the reason, I have no errors in my error.log file.

Surprisingly if I switch to Puma as a webserver everything is working fine.

The code that causes the issue in my application is marked with a comment:

  def build_redirect_url      raise ArgumentError.new("not implemented for provider") if checkout_settings[:package_provider] != "expedia_click_and_mix"      opts = {        :hotels            => [hotel],        :from_date         => from_date,        :to_date           => to_date,        :from_airport_code => from_airport.code,        :to_airport_code   => to_airport.code,        :number_of_adults  => number_of_adults.to_i,        :cache             => false,        :piid              => checkout_settings[:unique_identifier]      }      # the below line never finishes. takes like 30 seconds      searcher    = PackageKraken::ListKraken::HotelGrouper.new(opts)      details_url = searcher.search.first.details_url      filter_id   = search_filter_setting.id      build_filter_redirect_url(filter_id, "expedia_click_and_mix", hotel.id, details_url)    end  

We never make it past the searcher = line. It seems the process dies before. So what I did is check my nginx log file for issues, but I only have this. Hoever it seems to have a 499 error code.

This is what I have in my log file:

79.236.111.56 - - [02/Nov/2016:14:28:30 +0100] "GET /packages/package_redirect_url?checkout_settings=%7B%22package_identifier%22%3A%22v5-8a5c783c4b614f2d8018117d4c7fa1f5-8-8-1%22  %2C%22package_provider%22%3A%22expedia_click_and_mix%22%7D&from_airport_id=b2ccff00-2186-482e-a74f-6892c8fd7f77&from_date=2016-11-09+01%3A00%3A00+%2B0100&hotel_id=14245&number_of  _adults=1&to_airport_id=aabc5cd4-36e6-45c9-b027-e0ed4b209414&to_date=2016-11-15+01%3A00%3A00+%2B0100 HTTP/1.1" 499 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWeb  Kit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36"  

Here is my site config for the website:

server {    listen 80;    server_name tripl.de www.tripl.de;    return 301 https://$host$request_uri;  }    server {    listen 443;    server_name tripl.de;    ssl on;    ssl_certificate /etc/nginx/ssl/wildcard-cert.crt;    ssl_certificate_key /etc/nginx/ssl/wildcard-cert.key;    return 301 https://www.tripl.de$request_uri;  }    # Production server  server {    proxy_connect_timeout       600;    proxy_send_timeout          600;    proxy_read_timeout          600;    send_timeout                600;    listen 443;    server_name www.tripl.de;    ssl on;    ssl_certificate /etc/nginx/ssl/wildcard-cert.crt;    ssl_certificate_key /etc/nginx/ssl/wildcard-cert.key;      client_max_body_size 4G;    keepalive_timeout 60;    passenger_enabled on;    root         /home/deployer/app_production/current/public;    proxy_set_header        X-Forwarded-Proto https;    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  location / {       if ($request_method = 'OPTIONS') {          add_header 'Access-Control-Allow-Origin' '*';          add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';          #          # Custom headers and headers various browsers *should* be OK with but aren't          #          add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';          #          # Tell client that this pre-flight info is valid for 20 days          #          add_header 'Access-Control-Max-Age' 1728000;          add_header 'Content-Type' 'text/plain charset=UTF-8';          add_header 'Content-Length' 0;          return 204;       }       if ($request_method = 'POST') {          add_header 'Access-Control-Allow-Origin' '*';          add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';          add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';       }       if ($request_method = 'GET') {          add_header 'Access-Control-Allow-Origin' '*';          add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';          add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';       }  }    }  

And this is what I have in my passenger.conf:

passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;  passenger_ruby /home/deployer/.rbenv/shims/ruby;  

Any ideas what could be wrong?

Thanks

Search for model with multiple properties (where properties are in a key => value table)

Posted: 02 Nov 2016 07:36 AM PDT

I have a model called Document, and a has_many relation with DocumentProperty.

DocumentProperty has a id, document_id, key, and value column.

I'm trying to come up with a query that will let me search for a document with two or more key => value pairs, e.g a document with size = A4 and pages = 2, but I can't find a way to do that without writing all of the SQL myself (currently using an ActiveRecord::Relation).

Example table data:

| document_id | key    | value   |  +-------------+--------+---------+  | 1           | size   | A4      |  | 1           | pages  | 2       |  | 2           | size   | A4      |  | 2           | pages  | 3       |  | 3           | size   | A4      |  | 3           | pages  | 2       |  | 3           | author | Brandon |  

With my search, document 1 and 3 should be returned.

Does Rails support this?

How can I override the .. and ... operators of Ruby Ranges to accept Float::INFINITY?

Posted: 02 Nov 2016 06:13 AM PDT

I want to override the .. and ... operators in Ruby's Range.

Reason is, I'm working with infinite date ranges in the database. If you pull an infinty datetime out of Postgres, you get a Float::INFINITY in Ruby.

The problem with this is, I cannot use Float::INFINITY as the end of a range:

Date.today...Float::INFINITY  => Wed, 02 Nov 2016...Infinity     DateTime.now...Float::INFINITY  # ArgumentError: bad value for range    Time.now...Float::INFINITY  # ArgumentError: bad value for range  

... yet I use .. and ... syntax quite often in my code.

To even be able to construct the range, you need to use DateTime::Infinity.new instead:

Date.today...DateTime::Infinity.new  => Wed, 02 Nov 2016...#<Date::Infinity:0x007fd82348c698 @d=1>     DateTime.now...DateTime::Infinity.new  => Wed, 02 Nov 2016 12:57:07 +0000...#<Date::Infinity:0x007fd82348c698 @d=1>     Time.now...DateTime::Infinity.new  => 2016-11-02 12:57:33 +0000...#<Date::Infinity:0x007fd82348c698 @d=1>   

But I would need to do the the Float::INFINITY -> DateTime::Infinity.new conversion every time:

model.start_time...convert_infinity(model.end_time)

Is there a way I can override the .. and ... operators so that I can incorporate the conversion function and keep the syntactic sugar?

Refreshing views by redirect back while preserving scroll location in Rails

Posted: 02 Nov 2016 06:00 AM PDT

I'm building an Instagram-like app in rails. You can submit a post, vote on posts (via act_as_votable) and comment on others' posts.

My issue comes when the user votes or adds a comment to a post. I'd like those changes to be reflected in the views instantly with something simple (i.e. without using Ajax).

Currently I'm reflecting the changes by using redirect_to forcing a reload

#as an example here an upvote action in my posts controller      def upvote        @post.vote_by voter: current_user, duplicate: true        flash[:info] = "Your vote has been recorded"        redirect_to posts_path    end  

Although this works, the scroll bar jumps to the top of the page after each reload making it a nightmare for the user to scroll back down to the position he was every time he votes or add a comment.

I've tried many things so far to try to preserve the scroll location after reload without success, among those:

1)After I noticed that a browser reload preserves the scroll location, I tried to implement a simple JS solution by adding a click event listener that reloads the page with the code below.

$(document).ready(function() {    $('.class_of_link_tag').click(function() {        window.location.reload(true);    });  });  

This maintains the scroll position if applied to any div but for some reason when there's a link_to tag involved the click is not listened and the page doesn't get reloaded.

2)Tried to implement 'Scroll Sneak' (http://mrcoles.com/blog/scroll-sneak-maintain-position-between-page-loads/). In a very weird way it worked at first and at some point stopped working. It's been impossible to pinpoint why. I've basically included the JS source (http://mrcoles.com/media/js/scroll-sneak.js) in application.js and appended this script at the bottom of body.

  (function() {        var sneaky = new ScrollSneak(location.hostname), posts = document.getElementsByClassName('vote-icon'), i = 0, len = posts.length;        for (; i < len; i++) {            posts[i].onclick = sneaky.sneak;        }    })();  

'vote-icon' is the class of the div containing the link to the 'posts#upvote'

  <!--a portion of the posts index.html.erb -->      <div class="vote-icon">        <%= link_to vote_path(post_id: post.id), method: :put do %>        <%= image_tag("vote.png", :height => 45)  %>        <% end %>      </div>  

I'm getting to a point of desperation here! Could you give me some guidance on how could I solve this? Is it possible to use window.location.reload in a link so it invokes the controller action and reloads the browser via JS subsequently? How could I approach this issue to get the best UX without using Ajax?

Thanks

Rails sum method returns undefined

Posted: 02 Nov 2016 06:02 AM PDT

Generating the following error undefined method +' for #<Debit

where the controller action defines

@debits = Debit.order("vatunitid ASC").where('unit_id = ? AND folio_id = ?', session[:unit_id], @folio.id).to_a  @adhoc_folios = Folio.order("created_at asc").where(['checkout IS NULL AND unit_id = ? AND id != ?', session[:unit_id], @folio.id]).all  @vatunits = Vatunit.where(['unit_id = ?', session[:unit_id]]).to_a  @rates = @debits.map(&:vatunitid).uniq  

and presently in the view (for testing purposes)

 @rates.each do |rate|      @debits_for_rate = @debits.select{ |i| i.vatunitid == rate }      @debits_for_rate.count      @debits_for_rate.sum(:amount)   

The count instruction returns a proper value
The call to sum is deemed at this point inexistent.

How did this come about and how to overcome it?

RoR Ransack how to add own sql + form option

Posted: 02 Nov 2016 05:53 AM PDT

I have an sql query in RoR: "DATE_FORMAT(CURDATE() ,'%m-%d')= DATE_FORMAT(#{field_name} ,'%m-%d')" for searching users that have birthdays today. I want to add it to ransack form, to be chosen on webpage. Tried Ransack.configure but I can't get how implement in it custom sql. Is it possible and what's the best way to do it?

Active-sqlserver-adapter with Rails 5 application.

Posted: 02 Nov 2016 05:34 AM PDT

I am trying to set up a new application with rails 5. I have a half dozen applications working fine with rails 4.x.

When I try to do a bundle install, I get an error that starts with

Error:[rake --tasks] DEPRECATION WARNING: alias_method_chain is deprecated. Please, use Module#prepend instead. From module, you can access the original method using super. (called from <top (required)> at C:/Users/cmendla/RubymineProjects/user_message_console/config/application.rb:7)  DEPRECATION WARNING: alias_method_chain is deprecated. Please, use Module#prepend instead. From module, you can access the original method using super. (called from <top (required)> at C:/Users/cmendla/RubymineProjects/user_message_console/config/application.rb:7)  rake aborted!  Bundler::GemRequireError: There was an error while trying to load the gem 'activerecord-sqlserver-adapter'.  Gem Load Error is: undefined method `add_order!' for class `Class'  Backtrace for gem load error is:  

If I do a bundle show activerecord I get

C:\Users\cmendla\RubymineProjects\user_message_console>bundle show activerecord  C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-5.0.0.1  

I've tried both a plain gem and a gem with different versions

gem 'tiny_tds'  # gem 'activerecord-sqlserver-adapter', '~> 5.0.0'   gem 'activerecord-sqlserver-adapter'  

A bundle install shows an error code of 0

Using activerecord-sqlserver-adapter 2.3.8  (this is a partial list ).....  Using sprockets-rails 3.2.0  Using coffee-rails 4.2.1  Using jquery-rails 4.2.1  Using web-console 3.4.0  Using rails 5.0.0.1  Using sass-rails 5.0.6  Bundle complete! 14 Gemfile dependencies, 58 gems now installed.  Use `bundle show [gemname]` to see where a bundled gem is installed.    Process finished with exit code 0  

But then I get the error that I posted above . There server I am using is server 2012

There is some info at https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/tree/rails5 but it doesn't seem clear as to if I am loading the right gem version as that document references gem 'activerecord-sqlserver-adapter', '~> 4.2.0'

If anyone knows of compatibility issues between rails 5 and the ActiveRecord SQL Server Adapter, I can stay with rails 4.x for a bit. Otherwise, I'd like to try to get this working.

Rails - How to host static assets on S3 with Heroku

Posted: 02 Nov 2016 06:07 AM PDT

I have a rails 5 app I'm about to deploy.

the image folder is over 300 Mb (over the limit of heroku's deploy size) So I've uploaded all the images to S3 however, Heroku is still precompiling and the build is failing because of the slug size.

Can anyone point me to articles or help me solve the following problems?

  • Precompile Assets and send them to S3
  • Use CloudFront with my S3 Bucket (Do I need cloud front?)
  • How to Understand bucket policies and how they relate to cloud front / hosting.
  • Actually bypass the 300Mb limit of slug size on heroku and get this app deployed

much appreciated!

Ruby on Rails Tutorial by Michael Hartl - no route action, but it's in the routes.rb

Posted: 02 Nov 2016 07:43 AM PDT

Update - typical user error - guys thanks for all the technical help! It looks like the password_reset_controller_test should have never been made. For some reason - my control exists even though there was a "--no-test-framework" used in 12.1.1. I'm pretty sure I mistyped something & that's why the tutorial doesn't have a ID for the user on it. To recap: the solution was removing the controller test - as there's an integration test made later.

I've got an issue with an error claiming no route, but can clearly see the route in the routes.rb file & in the rake routes. I'm using Michael Hartl's Ruby on Rails tutorial guide. In chapter 12, I've got a failing test. I tested this by removing and adding back several parts - it appears to actually be in the controller, even though it claims no action found. I also checked for params issues as best as I know how with my limited knowledge.

Any hints would be appreciated!

Thanks ...

ERROR["test_should_get_edit", PasswordResetsControllerTest, 2016-10-20 15:24:37 +0000]   test_should_get_edit#PasswordResetsControllerTest (1476977077.08s)  ActionController::UrlGenerationError:         ActionController::UrlGenerationError: No route matches {:action=>"edit", :controller=>"password_resets"}              test/controllers/password_resets_controller_test.rb:11:in `block in <class:PasswordResetsControllerTest>'          test/controllers/password_resets_controller_test.rb:11:in `block in <class:PasswordResetsControllerTest>'      54/54: [=======================================================================] 100% Time: 00:00:03, Time: 00:00:03    Finished in 3.02339s  54 tests, 279 assertions, 0 failures, 1 errors, 0 skips  

Controller Test

password_resets_controller_test      require 'test_helper'        class PasswordResetsControllerTest < ActionController::TestCase          test "should get new" do          get :new          assert_response :success        end          test "should get edit" do          get :edit          assert_response :success        end      end  

Routes.rb

Rails.application.routes.draw do    root   'static_pages#home'    get    '/help',    to: 'static_pages#help'    get    '/about',   to: 'static_pages#about'    get    '/contact', to: 'static_pages#contact'    get    '/signup',  to: 'users#new'    get    '/login',   to: 'sessions#new'    post   '/login',   to: 'sessions#create'    delete '/logout',  to: 'sessions#destroy'      resources :users    resources :account_activations, only: [:edit]    resources :password_resets,     only: [:new, :create, :edit, :update]    resources :microposts,          only: [:create, :destroy]  end  

Controller file

class PasswordResetsController < ApplicationController    before_action :get_user,         only: [:edit, :update]    before_action :valid_user,       only: [:edit, :update]    before_action :check_expiration, only: [:edit, :update]    # Case (1)      def new    end      def create      @user = User.find_by(email: params[:password_reset][:email].downcase)      if @user        @user.create_reset_digest        @user.send_password_reset_email        flash[:info] = "Email sent with password reset instructions"        redirect_to root_url      else        flash.now[:danger] = "Email address not found"        render 'new'      end    end      def edit    end      def update      if params[:user][:password].empty?        @user.errors.add(:password, "can't be empty")        render 'edit'      elsif @user.update_attributes(user_params)        log_in @user        @user.update_attribute(:reset_digest, nil)        flash[:success] = "Password has been reset."        redirect_to @user      else        render 'edit'      end    end        private        def user_params        params.require(:user).permit(:password, :password_confirmation)      end        # Before filters        def get_user        @user = User.find_by(email: params[:email])      end        # Confirms a valid user.      def valid_user        unless (@user && @user.activated? &&                @user.authenticated?(:reset, params[:id]))          redirect_to root_url        end      end        # Checks expiration of reset token.      def check_expiration        if @user.password_reset_expired?          flash[:danger] = "Password reset has expired."          redirect_to new_password_reset_url        end      end  end  

Here's rake routes file - if I read this right there's an edit option in there ... also the editing of the route file when I remove the resource gets a different error message.

rake routes                   Prefix Verb   URI Pattern                             Controller#Action                     root GET    /                                       static_pages#home                     help GET    /help(.:format)                         static_pages#help                    about GET    /about(.:format)                        static_pages#about                  contact GET    /contact(.:format)                      static_pages#contact                   signup GET    /signup(.:format)                       users#new                    login GET    /login(.:format)                        sessions#new                          POST   /login(.:format)                        sessions#create                   logout DELETE /logout(.:format)                       sessions#destroy                    users GET    /users(.:format)                        users#index                          POST   /users(.:format)                        users#create                 new_user GET    /users/new(.:format)                    users#new                edit_user GET    /users/:id/edit(.:format)               users#edit                     user GET    /users/:id(.:format)                    users#show                          PATCH  /users/:id(.:format)                    users#update                          PUT    /users/:id(.:format)                    users#update                          DELETE /users/:id(.:format)                    users#destroy  edit_account_activation GET    /account_activations/:id/edit(.:format) account_activations#edit          password_resets POST   /password_resets(.:format)              password_resets#create       new_password_reset GET    /password_resets/new(.:format)          password_resets#new      edit_password_reset GET    /password_resets/:id/edit(.:format)     password_resets#edit           password_reset PATCH  /password_resets/:id(.:format)          password_resets#update                          PUT    /password_resets/:id(.:format)          password_resets#update               microposts POST   /microposts(.:format)                   microposts#create                micropost DELETE /microposts/:id(.:format)               microposts#destroy  

Formatting Bootstrap links on Ruby on Rails

Posted: 02 Nov 2016 05:39 AM PDT

I am trying to have a navigation bar at the top of my site, and aligned to the right a Log Out link only when the user is logged in. I have this:

<nav class="navbar navbar-dark bg-inverse">    <%= link_to "Simpleref", root_path, :class => "navbar-brand" %>    <ul class="nav navbar-nav">      <% ((user_signed_in?)? @nav_items_user : @nav_items).each do |i| %>        <li class="nav-item <%= 'active' if current_page?(i[:url]) %>">          <a href="<%= i[:url] %>" class="nav-link"><%= i[:name] %>            <% if current_page?(i[:url]) %> <span class="sr-only">(current)</span><% end %>          </a>        </li>      <% end %>     </ul>       <% if user_signed_in? %>        <ul class = "nav pull-right">      <%= link_to "Log out", destroy_user_session_path, :method => :delete %>    </ul>    <% end %>  </nav>  

What is wrong? I get a navbar with the Logout link to the left and higher than the references and home links.

Unable to disable font awesome

Posted: 02 Nov 2016 05:28 AM PDT

I have created Rails app and I am using bootstrap views. I am unable to disable font awesome. The code I have used as follows

   <td>        <%= back_up.db_size %> <a href="<%= back_up.db_link%>"><i class="fa fa-download pull-right p-c-t-4 <%= back_up.db_size == 0  ? 'disabled' : '' %> "></i></a>     </td>  

I don't know what was wrong here. I need when page load back_up size will be displayed with download icon, suppose backup size is zero then the size displayed with disabled link.

RSolr::Error::Http - 400 Bad Request - Missing solr core name in path

Posted: 02 Nov 2016 04:41 AM PDT

I would like to send json data from my android app to a ruby on rails webApp which uses solr search engine. But every time I send data, I get this error message :

RSolr::Error::Http - 400 Bad Request Error: Apache Tomcat/7.0.68 (Ubuntu) - Rapport d''erreur

Etat HTTP 400 - Missing solr core name in path

type Rapport d''état

message Missing solr core name in path

description La requête envoyée par le client était syntaxiquement incorrecte.

Apache Tomcat/7.0.68 (Ubuntu)

URI: http://localhost:8080/solr/update?wt=ruby Request Headers: {"Content-Type"=>"text/xml"} Request Data: "" Backtrace: /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rsolr-1.1.1/lib/rsolr/client.rb:288:in adapt_response' /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rsolr-1.1.1/lib/rsolr/client.rb:189:inexecute' /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rsolr-1.1.1/lib/rsolr/client.rb:175:in send_and_receive' /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sunspot_rails-2.2.5/lib/sunspot/rails/solr_instrumentation.rb:16:inblock in send_and_receive_with_as_instrumentation' /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/notifications.rb:164:in block in instrument' /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/notifications/instrumenter.rb:20:ininstrument' /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.2.5.1/lib/active_support/notifications.rb:164:in instrument' /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sunspot_rails-2.2.5/lib/sunspot/rails/solr_instrumentation.rb:15:insend_and_receive_with_as_instrumentation' (eval):2:in post' /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rsolr-1.1.1/lib/rsolr/client.rb:84:inupdate' /home/wivi/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/rsolr-1.1.1/lib/rsolr/client.rb:113:in `commit'

I have tried many things but without success. Is there anybody who has an idea to resolve this problem ? Thanks in advance for your help.

Best regards,

Association fails on nested creation when using accepts_nested_attributes_for

Posted: 02 Nov 2016 04:46 AM PDT

The problem is as follows: three models, relatively speaking, a Tree, an Ancestor and a Descendant, and I want to update/create/delete records via nested forms, like Tree->Ancestor->Descendant, so I set this up using accepts_nested_attributes_for:

class Tree < ActiveRecord::Base     has_many :ancestors, inverse_of: :tree       accepts_nested_attributes_for :ancestors  end      class Ancestor < ActiveRecord::Base     has_many :descendants, inverse_of: :ancestor     belongs_to :tree, inverse_of: :ancestors       accepts_nested_attributes_for :descendants       # should always have a tree     validates :tree_id, presence: true  end    class Descendant < ActiveRecord::Base     belongs_to :ancestor, inverse_of: :descendants       # should always have an ancestor     validates :ancestor_id, presence: true  end  

inverse_of is recommended in the docs (and a lot of other articles elaborating on the subject) to ensure that parent and child records are associated correctly:

Parameters are below:

parameters = {    id: 1,    name: 'TREE'    ancestors_attributes: [      {        name: 'ANCESTOR'        descendants_attributes: [          {name: 'DESCENDANT'}        ]      }    ]    }  

But after all the setting up I got an error after running tests: when I was creating nested Descendants theirs ancestor_ids were empty.

Although, when I did try to save Descendents just through an existing Ancestor it did create records successfully without any errors, so my associations seem to be set correctly.

What can possibly be the problem?

Answer:

I haven't found an answer as obvious as thought it would be, so am posting it here: it turns out that one should use:

validates :ancestor, presence: true  

Instead of:

validates :ancestor_id, presence: true  

To ensure that parent and child records are associated correctly.

Docs:

If you want to validate that a child record is associated with a parent record, you can use the validates_presence_of method and the :inverse_of key

P.S. No doubt, it is surely a mistake made because of my inattention, but I still have a feeling that this behaviour of validates is not transparent at all.

Authenticate user in controller and then redirect

Posted: 02 Nov 2016 06:45 AM PDT

I have the following code under projects_controller.rb

class Admin::ProjectsController < ApplicationController  before_filter :require_login    def require_login    while (adminLogin != 'username')      redirect_to admin_login_path and return    end  end  

And this under application_controller.rb

class ApplicationController < ActionController::Base    # Return the admin user   def adminLogin     @email = params[:email]     @password = params[:password]     return @email   end  end  

I am trying to get the email in that form and pass it to the projects controller so when the email is defined, the admin can log in. When I press the submit button on the form I can see the right email being sent to the projects controller by using <%= debug @email %> in the form, but the page redirects to login again. How can I then go to /projects?

[UPDATE]:

application_controller.rb

class ApplicationController < ActionController::Base  protect_from_forgery    # Return the admin user    def redirect_unless_admin  @email = params[:email]  password = params[:password]  if (@email == 'username')    redirect_to admin_projects_path  else     redirect_to admin_login_path  end  

end end

and I require this method in my projects_controller.rb. This is just breaking it, redirecting too many times

config.eager_load causes production application to crash

Posted: 02 Nov 2016 03:58 AM PDT

I just upgraded my application to Rails 5. It works just fine in development and Staging environments, but crashes once in production. It seems to come from the config.eager_load = true line, from production.rb.

I configured the app for maximum verbose in logs, but logs are empty, all I get is the following message:

at=error code=H10 desc="App crashed"   

Is there anything more to configure in Rails 5 when eager_load is set to true ? I searched though the config tutorial, couldn't find anything.

DB setup for heroku review apps failed suddenly

Posted: 02 Nov 2016 03:53 AM PDT

Previously same script creating DB for review apps. But, all of sudden db setup starts failing because ENV['HEROKU_APP_NAME'] is not available in post-deploy script.


setupdevdb.py(script to setup dev DB)

if ENV.key?('HEROKU_APP_NAME')    resetdevdb(ENV['HEROKU_APP_NAME'])  else    puts "Please specify a db name"  end  

app.json (review app)

{    "name": "app",    "scripts": {      "postdeploy": "setupdevdb"    },    "env": {      "BUILDPACK_URL": "https://github.com/ddollar/heroku-buildpack-multi.git",      "BUNDLE_WITHOUT": "development:test",      "RACK_ENV": "staging",      "RAILS_ENV": "staging",      "WEB_CONCURRENCY": "2",      "DATABASE_URL_BASE": "postgres://username:some@some.base-url.com:port/",      "HEROKU_APP_NAME": {        "required": true      }    },    "addons": [      "sendgrid",      "memcachier",      "rediscloud"    ]  }  

jruby trouble with warbler aborted

Posted: 02 Nov 2016 03:39 AM PDT

I'm a beginner in jruby. I have a Ruby Rails app - which I run with rials s to run. Now I want to create war-warbler with a WAR-file, but I get an error with which I can do nothing:

double loading C:/jruby-9.1.5.0/lib/ruby/gems/shared/gems/activerecord-jdbc-adapter-1.3.21/lib/arjdbc/tasks/databases.rake please delete lib/tasks/jdbc.rake if present! warble aborted! NoMethodError: undefined method tail' for nil:NilClass Did you mean? taint rakefile:1:in' rakefile:6:in <main>' C:/Hagen/leaman/lib/tasks/warbler/warbler.rake:1:in' C:/Hagen/leaman/lib/tasks/warbler/warbler.rake:2:in <main>' rakefile:1:in' rakefile:6:in <main>' C:/Hagen/leaman/lib/tasks/warbler/warbler.rake:1:in' C:/Hagen/leaman/lib/tasks/warbler/warbler.rake:2:in <main>' rakefile:1:in' rakefile:6:in `'

facts: windows7 Jruby-9.1.5.0 Warbler (2.0.4)

Ruby On Rails, Error running command "rails generate controller", Input/output error @ rb_sysopen, (Errno::EIO)

Posted: 02 Nov 2016 03:28 AM PDT

In the beginning, when I run rails generate controller welcome homepage into my project's dir, the command works OK and produces the app/controllers/welcome_controller.rb and route get welcome/homepage

User1@My-Machine:~/MyProject$ rails generate controller welcome homepage  /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/app_rails_loader.rb:39: warning: Insecure world writable dir /home/User1/.rbenv/versions in PATH, mode 040777        create  app/controllers/welcome_controller.rb         route  get 'welcome/homepage'  

immediately after that, the command runs into the following error:

/home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:98:in `binread': Input/output error @ rb_sysopen - /home/User1/MyProject/config/routes.rb (Errno::EIO)  

followed by a list of files.

        from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:98:in `replace!'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:59:in `invoke!'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:94:in `action'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:30:in `insert_into_file'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/generators/actions.rb:224:in `block in route'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:194:in `block in in_root'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:184:in `block in inside'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/2.3.0/fileutils.rb:128:in `chdir'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/2.3.0/fileutils.rb:128:in `cd'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:184:in `inside'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:194:in `in_root'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/generators/actions.rb:223:in `route'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/generators/rails/controller/controller_generator.rb:16:in `block in add_routes'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/generators/rails/controller/controller_generator.rb:15:in `reverse_each'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/generators/rails/controller/controller_generator.rb:15:in `add_routes'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/command.rb:27:in `run'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:126:in `invoke_command'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `block in invoke_all'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `each'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `map'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `invoke_all'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/group.rb:232:in `dispatch'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/base.rb:440:in `start'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/generators.rb:157:in `invoke'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/generate.rb:13:in `<top (required)>'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:123:in `require_command!'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:130:in `generate_or_destroy'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:50:in `generate'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from /home/User1/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'          from bin/rails:4:in `require'          from bin/rails:4:in `<main>'  

Does anyone know how this can be resolved?

Rails - map 1 to true in if statement

Posted: 02 Nov 2016 04:24 AM PDT

I am getting a request from mobile app. They are sending a variable isbookmarked that can be either 1 or 0. I am checking in if statement.

if isbookmarked    do something  else    do something  end  

The else part is never executed because 0 is not recognised as false

How can I achieve this?

1 comment:

  1. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. Ruby on Rails Online Course Bangalore

    ReplyDelete