Thursday, July 21, 2016

Rails 4: Heroku push rejected / Gemfile Issues / GIT Issues | Fixed issues

Rails 4: Heroku push rejected / Gemfile Issues / GIT Issues | Fixed issues


Rails 4: Heroku push rejected / Gemfile Issues / GIT Issues

Posted: 21 Jul 2016 07:46 AM PDT

I am truly confused and your help and explanation will be much much appreciated.

1.] my gemfile currently is displayed as below:

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

2.] my gemlock file is currently displayed as below:

GEM    remote: https://rubygems.org/    specs:      actionmailer (4.1.10)        actionpack (= 4.1.10)        actionview (= 4.1.10)        mail (~> 2.5, >= 2.5.4)      actionpack (4.1.10)        actionview (= 4.1.10)        activesupport (= 4.1.10)        rack (~> 1.5.2)        rack-test (~> 0.6.2)      actionview (4.1.10)        activesupport (= 4.1.10)        builder (~> 3.1)        erubis (~> 2.7.0)      activemodel (4.1.10)        activesupport (= 4.1.10)        builder (~> 3.1)      activerecord (4.1.10)        activemodel (= 4.1.10)        activesupport (= 4.1.10)        arel (~> 5.0.0)      activesupport (4.1.10)        i18n (~> 0.6, >= 0.6.9)        json (~> 1.7, >= 1.7.7)        minitest (~> 5.1)        thread_safe (~> 0.1)        tzinfo (~> 1.1)      acts_as_commentable (4.0.2)      ansi (1.5.0)      arel (5.0.1.20140414130214)      awesome_print (1.6.1)      aws_cf_signer (0.1.3)      bcrypt (3.1.7)      better_errors (2.1.1)        coderay (>= 1.0.0)        erubis (>= 2.6.6)        rack (>= 0.9.0)      binding_of_caller (0.7.3.pre1)        debug_inspector (>= 0.0.1)      builder (3.2.2)      byebug (3.4.0)        columnize (~> 0.8)        debugger-linecache (~> 1.2)        slop (~> 3.6)      cancancan (1.13.1)      carrierwave (0.10.0)        activemodel (>= 3.2.0)        activesupport (>= 3.2.0)        json (>= 1.7)        mime-types (>= 1.16)      cloudinary (1.2.0)        aws_cf_signer        rest-client      cocoon (1.2.6)      coderay (1.1.0)      coffee-rails (4.0.1)        coffee-script (>= 2.2.0)        railties (>= 4.0.0, < 5.0)      coffee-script (2.4.1)        coffee-script-source        execjs      coffee-script-source (1.9.1.1)      columnize (0.9.0)      daemons (1.2.3)      debug_inspector (0.0.2)      debugger-linecache (1.2.0)      devise (3.5.2)        bcrypt (~> 3.0)        orm_adapter (~> 0.1)        railties (>= 3.2.6, < 5)        responders        thread_safe (~> 0.1)        warden (~> 1.2.3)      domain_name (0.5.20160615)        unf (>= 0.0.5, < 1.0.0)      erubis (2.7.0)      eventmachine (1.0.5)      execjs (2.6.0)      ffi (1.9.10)      font-awesome-rails (4.4.0.0)        railties (>= 3.2, < 5.0)      formatador (0.2.5)      foundation-datetimepicker-rails (0.2.1)      foundation-rails (5.3.1.0)        railties (>= 3.1.0)        sass (>= 3.2.0)      geocoder (1.2.11)      guard (2.13.0)        formatador (>= 0.2.4)        listen (>= 2.7, <= 4.0)        lumberjack (~> 1.0)        nenv (~> 0.1)        notiffany (~> 0.0)        pry (>= 0.9.12)        shellany (~> 0.0)        thor (>= 0.18.1)      guard-minitest (2.3.1)        guard (~> 2.0)        minitest (>= 3.0)      hike (1.2.3)      http-cookie (1.0.2)        domain_name (~> 0.5)      i18n (0.7.0)      jbuilder (2.3.1)        activesupport (>= 3.0.0, < 5)        multi_json (~> 1.2)      jquery-rails (3.1.4)        railties (>= 3.0, < 5.0)        thor (>= 0.14, < 2.0)      jquery-turbolinks (2.1.0)        railties (>= 3.1.0)        turbolinks      jquery-ui-rails (5.0.2)        railties (>= 3.2.16)      json (1.8.3)      jwt (1.5.1)      kgio (2.10.0)      listen (3.0.3)        rb-fsevent (>= 0.9.3)        rb-inotify (>= 0.9)      lumberjack (1.0.9)      mail (2.6.3)        mime-types (>= 1.16, < 3)      mailcatcher (0.6.1)        activesupport (>= 4.0.0, < 5)        eventmachine (~> 1.0.0, <= 1.0.5)        mail (~> 2.3)        sinatra (~> 1.2)        skinny (~> 0.2.3)        sqlite3 (~> 1.3)        thin (~> 1.5.0)      method_source (0.8.2)      mime-types (2.99.2)      mini_backtrace (0.1.3)        minitest (> 1.2.0)        rails (>= 2.3.3)      minitest (5.8.0)      minitest-reporters (1.0.5)        ansi        builder        minitest (>= 5.0)        ruby-progressbar      multi_json (1.11.2)      nenv (0.2.0)      netrc (0.11.0)      notiffany (0.0.8)        nenv (~> 0.1)        shellany (~> 0.0)      orm_adapter (0.5.0)      pg (0.17.1)      pry (0.10.1)        coderay (~> 1.1.0)        method_source (~> 0.8.1)        slop (~> 3.4)      public_activity (1.4.2)        actionpack (>= 3.0.0)        activerecord (>= 3.0)        i18n (>= 0.5.0)        railties (>= 3.0.0)      quiet_assets (1.1.0)        railties (>= 3.1, < 5.0)      rack (1.5.5)      rack-protection (1.5.3)        rack      rack-test (0.6.3)        rack (>= 1.0)      rails (4.1.10)        actionmailer (= 4.1.10)        actionpack (= 4.1.10)        actionview (= 4.1.10)        activemodel (= 4.1.10)        activerecord (= 4.1.10)        activesupport (= 4.1.10)        bundler (>= 1.3.0, < 2.0)        railties (= 4.1.10)        sprockets-rails (~> 2.0)      rails_12factor (0.0.3)        rails_serve_static_assets        rails_stdout_logging      rails_serve_static_assets (0.0.4)      rails_stdout_logging (0.0.4)      railties (4.1.10)        actionpack (= 4.1.10)        activesupport (= 4.1.10)        rake (>= 0.8.7)        thor (>= 0.18.1, < 2.0)      raindrops (0.15.0)      rake (11.1.2)      rb-fsevent (0.9.6)      rb-inotify (0.9.5)        ffi (>= 0.5.0)      rdoc (4.2.0)        json (~> 1.4)      responders (1.1.2)        railties (>= 3.2, < 4.2)      rest-client (1.8.0)        http-cookie (>= 1.0.2, < 2.0)        mime-types (>= 1.16, < 3.0)        netrc (~> 0.7)      rmagick (2.15.4)      ruby-progressbar (1.7.5)      sass (3.2.19)      sass-rails (4.0.5)        railties (>= 4.0.0, < 5.0)        sass (~> 3.2.2)        sprockets (~> 2.8, < 3.0)        sprockets-rails (~> 2.0)      sdoc (0.4.1)        json (~> 1.7, >= 1.7.7)        rdoc (~> 4.0)      shellany (0.0.1)      simple_form (3.1.1)        actionpack (~> 4.0)        activemodel (~> 4.0)      sinatra (1.4.6)        rack (~> 1.4)        rack-protection (~> 1.4)        tilt (>= 1.3, < 3)      skinny (0.2.3)        eventmachine (~> 1.0.0)        thin (~> 1.5.0)      slop (3.6.0)      social-share-button (0.1.8)        coffee-rails        sass-rails      spring (1.1.3)      sprockets (2.12.4)        hike (~> 1.2)        multi_json (~> 1.0)        rack (~> 1.0)        tilt (~> 1.1, != 1.3.0)      sprockets-rails (2.3.3)        actionpack (>= 3.0)        activesupport (>= 3.0)        sprockets (>= 2.8, < 4.0)      sqlite3 (1.3.9)      stripe (1.46.0)        rest-client (~> 1.4)      stripe_event (1.5.0)        activesupport (>= 3.1)        stripe (~> 1.6)      thin (1.5.1)        daemons (>= 1.0.9)        eventmachine (>= 0.12.6)        rack (>= 1.0.0)      thor (0.19.1)      thread_safe (0.3.5)      tilt (1.4.1)      turbolinks (2.5.3)        coffee-rails      twilio-ruby (4.5.0)        builder (>= 2.1.2)        jwt (~> 1.0)        multi_json (>= 1.3.0)      tzinfo (1.2.2)        thread_safe (~> 0.1)      uglifier (2.7.2)        execjs (>= 0.3.0)        json (>= 1.8.0)      unf (0.1.4)        unf_ext      unf_ext (0.0.7.2)      unicorn (4.8.3)        kgio (~> 2.6)        rack        raindrops (~> 0.7)      warden (1.2.3)        rack (>= 1.0)      web-console (2.0.0.beta3)        activemodel (~> 4.0)        binding_of_caller (= 0.7.3.pre1)        railties (~> 4.0)        sprockets-rails (>= 2.0, < 4.0)    PLATFORMS    ruby    DEPENDENCIES    acts_as_commentable    awesome_print    bcrypt (= 3.1.7)    better_errors    binding_of_caller    byebug (= 3.4.0)    cancancan (~> 1.10)    carrierwave    cloudinary    cocoon    coffee-rails (~> 4.0.0)    devise    font-awesome-rails    foundation-datetimepicker-rails    foundation-rails (= 5.3.1.0)    geocoder    guard-minitest (= 2.3.1)    jbuilder (~> 2.0)    jquery-rails    jquery-turbolinks    jquery-ui-rails    mailcatcher    mini_backtrace (= 0.1.3)    minitest-reporters (= 1.0.5)    pg (= 0.17.1)    polyamorous!    pry    public_activity    quiet_assets    rails (= 4.1.10)    rails_12factor    ransack!    rmagick    sass-rails (~> 4.0.3)    sdoc (~> 0.4.0)    simple_form    social-share-button    spring (= 1.1.3)    sqlite3 (= 1.3.9)    stripe    stripe_event    turbolinks    twilio-ruby    uglifier (>= 1.3.0)    unicorn (= 4.8.3)    web-console (= 2.0.0.beta3)  

3.] when ever i run bundle install some additional info gets added to my gemfile called GIT - i believe this is what is causing heroku not to accept deployment of my app

GIT    remote: git://github.com/activerecord-hackery/polyamorous.git    revision: 8f722a1edfaf20dbb14b21e422c629249a6fbfa6    specs:      polyamorous (1.3.1)        activerecord (>= 3.0)    GIT    remote: git://github.com/activerecord-hackery/ransack.git    revision: 742425ade4bb66db573dc13bf436a8f3c87b733b    branch: rails-4.1    specs:      ransack (1.2.4)        actionpack (>= 4.0)        activerecord (>= 4.0)        activesupport (>= 4.0)        i18n        polyamorous (~> 1.1)    GEM    remote: https://rubygems.org/    specs:      actionmailer (4.1.10)        actionpack (= 4.1.10)        actionview (= 4.1.10)        mail (~> 2.5, >= 2.5.4)      actionpack (4.1.10)        actionview (= 4.1.10)        activesupport (= 4.1.10)        rack (~> 1.5.2)        rack-test (~> 0.6.2)      actionview (4.1.10)        activesupport (= 4.1.10)  etc............  

4.] when i do git push heroku master i get the below error message:

Counting objects: 3218, done.  Delta compression using up to 4 threads.  Compressing objects: 100% (3089/3089), done.  Writing objects: 100% (3218/3218), 175.45 MiB | 602.00 KiB/s, done.  Total 3218 (delta 787), reused 0 (delta 0)  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:        You are trying to install in deployment mode after changing  remote:        your Gemfile. Run `bundle install` elsewhere and add the  remote:        updated Gemfile.lock to version control.  remote:        You have added to the Gemfile:  remote:        * source: git://github.com/activerecord-hackery/polyamorous.git (at master)  remote:        * source: git://github.com/activerecord-hackery/ransack.git (at rails-4.1)  remote:        Bundler Output: You are trying to install in deployment mode after changing  remote:        your Gemfile. Run `bundle install` elsewhere and add the  remote:        updated Gemfile.lock to version control.  remote:          remote:        You have added to the Gemfile:  remote:        * source: git://github.com/activerecord-hackery/polyamorous.git (at master)  remote:        * source: git://github.com/activerecord-hackery/ransack.git (at rails-4.1)  remote:  !  remote:  !     Failed to install gems via Bundler.  remote:  !  remote:  !     Push rejected, failed to compile Ruby app.  remote:   remote:  !     Push failed  remote: Verifying deploy...  remote:   remote: !   Push rejected to my-app-name.  remote:   To https://git.heroku.com/my-app-name.git   ! [remote rejected] master -> master (pre-receive hook declined)  error: failed to push some refs to 'https://git.heroku.com/my-app-name.git'  

could one kindly tell me exactly how to resolve this as i have no clue. i apologise if it is a basic question, but your help would be much much appreciated

Rails Savon gem keys in upper and lower case

Posted: 21 Jul 2016 07:31 AM PDT

I'm using the Savon gem to access a SOAP API. The thing is, the API requires keys in uppercase and other keys in lowercase, so I can't use the option convert_request_keys_to parameter.

This is the format of the API I need to comply to:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xs="XmlServices">     <soapenv:Header/>     <soapenv:Body>       <xs:GetRooms>           <xs:request>               <xs:Credentials>                    <xs:Credential1>"example1"</xs:Credential1>                   <xs:Credential2>"example2"</xs:Credential2>                   <xs:Credential3>"example3"</xs:Credential3>           </xs:Credentials>       </xs:request>   </xs:GetRooms>  

As you can see request is lowercase, and all the rest is uppercase.

This is how I use the gem:

def call(method, attributes = nil)    attributes = { 'request': { 'Credentials': attributes } }    response = client.call(method, message: attributes)    #do something with response  end  

Am I calling it right? Is there any option I'm missing? Will I need to fork the repository and modify the gem myself?

Show validation error for nested attributes

Posted: 21 Jul 2016 07:34 AM PDT

I have two model with following association

class Article < ActiveRecord::Base      has_many :categories      accepts_nested_attributes_for :categories, reject_if: proc { |attributes| (attributes['user_id'].blank? || attributes['numbers'].blank?) }, :allow_destroy => true  end  

and

class Category < ActiveRecord::Base  belongs_to :article    before_save :mytest      def mytest      self.article.phase != Category::STD["author"] && self.article.user_id == self.user_id    end  end  

Now if the validation of mytest method fails then article does not save. This is expected behavior. But this does not give any error message. I want to show an error message "You are not admin" if mytest method fails. How can I do that. I want to show the error as flash notice.

Rails: no implicit conversion of nil into String

Posted: 21 Jul 2016 07:52 AM PDT

I get arrays of different urls from a database column. Both are used to apply a whitelist on a url (ex. www.example.com/test/page.html). One is for the url beginning, one for the end.

whitelist_start = self.domain.whitelists.map(&:url_start)  whitelist_end   = self.domain.whitelists.map(&:url_end)  

Before I insert my url in the database, I want to check if save_url is true. After that, the filtered url will be inserted. The url can ether start (ex. www.example.com/test) or end with an url (ex. page.html). But the whole whitelist can also be empty at the same time. One of these three things.

save_url   = url.starts_with?(*whitelist_start) || url.ends_with?(*whitelist_end) || whitelist_start.empty? || whitelist_end.empty?  

I'm using the * before the array name in starts_with? and ends_with? because I want to insert all array values there. However, if one array is empty (which is totally fine) I get this error and can't proceed.

no implicit conversion of nil into String  

Is there a way to solve this?

Ruby on Rails migration rake [duplicate]

Posted: 21 Jul 2016 07:16 AM PDT

This question already has an answer here:

After rake db:migrate I get this:

Gem::LoadError: You have already activated rake 11.2.2, but your Gemfile requires rake 11.1.2.

What should I do?

Ruby on Rails: Update a Partial based on click of a hyperlink

Posted: 21 Jul 2016 07:08 AM PDT

Page on Landing shows a set of topics(list of hyperlinks) on left side, with sub-topics(list of hyperlinks) associated with each topic on the right side.

#Left Side - Topics  = column spacing:'none', widescreen_spacing:'none', position:'first', widescreen_position:'first' do    = card({}) do      = body({class:'card'}) do        .content          .topics            %ul              - @topics.each do |topic|                %li{class: ("selected" if topic == @topics[0])}                  %a                    = topic.title  #Right Side - SubTopics  = sub_topics({})  

sub_topics partial

- attr = args[:attr]    = column widescreen_spacing:'none', position:'last', widescreen_position:'last' do    = card({}) do      = body({class:'card'}) do        .content          .topic-detail            .topic-detail-title              = @sub_topics_title              .topics.topics-secondary                %ul                  - @sub_topics.each do |topic|                    %li                      %a{href: "{topic.id}"}                        = topic.title  

On landing, in the controller

def index      root_node = Help.new()      @topics = root_node.topics        if @topics.size >= 1          child_node = Help.new(@topics[0].id)        @sub_topics_title = @topics[0].title        @sub_topics = child_node.topics      end  end  

I am beginner to Ruby on Rails and the concept of using JS with RoR.

When a topic is clicked, @sub_topics should be populated again and the partial sub_topics should be re-rendered. Basically, i need to run this logic again with the id passed from the link.

child_node = Help.new(@topics[0].id)  @sub_topics_title = @topics[0].title  @sub_topics = child_node.topics  

What is the best way to achieve this ?

How to override class_method in rails model concern

Posted: 21 Jul 2016 07:56 AM PDT

How does one override a class method defined in a model concern?

This is a bit tricky since you're not really overriding a class method right? Because it's using the concern api of definining class methods in the class_methods block.

so say I have a concern that looks like this:

module MyConcern    extend ActiveSupport::Concern      class_methods do      def do_something         #some code      end    end    end  

In model.. how would I override that method so that I could call it like we do with super when using inheritance? So in my model I'd like to go:

def self.do_something    #call module do_something  end  

?

How would I convert this curl command into an AngularJS $http request?

Posted: 21 Jul 2016 06:54 AM PDT

I'm currently working on a project with a Rails backend and I need some help with translating this curl command please. We're using devise to allow a user to sign in but I'm not sure how to implement this into a AngularJS $http request.

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://localhost:3000/users -d

"{\"user\":{\"email\":\"user@example.com\",\"password\":\"password\"}}"

Find record with hash value in rails

Posted: 21 Jul 2016 06:47 AM PDT

I have one table called posts

create_table "posts", force: :cascade do |t|     t.text     "values"  end  

My record values are

#<Post id: 1, values: {"p1"=>"1", "p2"=>"xyz"}>  #<Post id: 2, values: {"p1"=>"1", "p2"=>"abc"}>  

I want to find record from post where values[:p2] = "abc"

Rails JS conditionally display div based on the radio button selected

Posted: 21 Jul 2016 07:51 AM PDT

$('.domestic_select, .abroad_select').on('click', function(){      alert($(this).val());      if($(this).val() == "true") {        $('#customer_goods').show();        $('#state_field').show();        $('#country_field').hide();        $('#change_resident').show();      }      else {        $('#change_resident').hide();        $('#customer_goods').hide();        $('#country_field').show();        $('#state_field').hide();      }    });  
.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", id: "myselect", 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, Country.collect_country,{}, {class: "selectpicker add_class_country dropdown_country col-sm-3", title: "select country", "data-live-search": "true"})          %br  

Here i've hided the country div, so that the state field is being displayed initially. when clicked the abroad option the "country div" should be displayed and "state div" should be hided But what I got is both state and country fields are hided after selecting the abroad option. can someone plz help me.thanks in advance

Form field parameters get messed up

Posted: 21 Jul 2016 06:27 AM PDT

I am submitting a form, this is the part in question

<% item.question_options.sort.each do |opt| %>    <%= radio_button_tag('responder[selected_options][' + item.id.to_s + '][][option_id]', opt.id.to_s, @responder.answered_to?(opt, item))%>     <%= text_field_tag('responder[selected_options][' + item.id.to_s + '][][content]', @responder.get_response_for_option(item, opt, lang.id)%>  <% end %>  

These are the generated tags. There are two questions, each is a radio button with an optional text field.

<input id="responder_selected_options_183__option_id_137" type="radio" value="137" name="0701b[selected_options][183][][option_id]">  <input id="responder_selected_options_183__content" type="text" name="0701b[selected_options][183][][content]">    <input id="responder_selected_options_183__option_id_138" type="radio" value="138" name="0701b[selected_options][183][][option_id]">  <input id="responder_selected_options_183__content" type="text" name="0701b[selected_options][183][][content]">  

If the first radio button chosen, and content given to the corresponding field, it creates parameters as expected:

"183"=>[{"option_id"=>"137", "content"=>"smth"}, {"content"=>""}]  

However, if the content is given to the first field and the second radio button is chosen, the parameters are like this:

"183"=>[{"content"=>"smth", "option_id"=>"138"}, {"content"=>""}]  

..while I would expect them to be like this:

"183"=>[{"content"=>"smth"}, {"option_id"=>"138", "content"=>""}]  

Why does this happen and how could I fix this?

Thanks!

Facebooj Posting Photo and getting the Likes and Comments on that Photo

Posted: 21 Jul 2016 06:23 AM PDT

I am using Koala Gem to post Photo to Facebook. After i post it i get the following response

{"id"=>"10210538952256401", "post_id"=>"10209794139276542_10210538952256401"}  

Now i want to check the Comments and Likes and how many people have shared the Photo.

post_id seems to be giving results for the Album and not the photo itself.

How to count total number of values as they appear inside a table

Posted: 21 Jul 2016 06:37 AM PDT

I have a table called Sales. And i have a field called plate_number corresponding to a single car.

How can i find the total number of instances of each car in db.

E.g [ [plate_number1, 10 times found], [plate_number2, 5 times found] ]

I tried using

Sale.map(&:plate_number).count and Sale.pluck(:plate_number)

but these just do a simple count of that column

any help appreciated

Unable to find distance between two coordinates by using ST_Distance in postgis and rails 4

Posted: 21 Jul 2016 06:03 AM PDT

I have a vendors model with the following schema

create_table "vendors", force: :cascade do |t|  t.string   "name"  t.decimal  "latitude",   precision: 9, scale: 6  t.decimal  "longitude",  precision: 9, scale: 6  t.datetime "created_at",                         null: false  t.datetime "updated_at",                         null: false  end  

I populated the database with Faker gem and few hard coded values to get the longitude and latitude

I need to find the near by vendors within a particular given distance .I was able to achieve this with the following code in my vendor.rb

scope :close_to, -> (latitude, longitude, distance_in_meters = 2000) {        where(%{          ST_DWithin(            ST_GeographyFromText(              'SRID=4326;POINT(' || vendors.longitude || ' ' ||               vendors.latitude || ')'            ),            ST_GeographyFromText('SRID=4326;POINT(%f %f)'),            %d          )        } % [longitude, latitude, distance_in_meters])      }  

So if I call

Vendor.close_to(39.000000, -76.000000, 500)   

in my rails console I get four rows. Now I need to find the actual distance between each of these row co-ordinates and the mentioned co-ordinate in close_to scope.In order to achieve that I wrote the following code in vendor.rb

class Vendor < ActiveRecord::Base  scope :close_to, -> (latitude, longitude, distance_in_meters = 2000) {        where(%{          ST_DWithin(            ST_GeographyFromText(              'SRID=4326;POINT(' || vendors.longitude || ' ' ||                vendors.latitude || ')'            ),            ST_GeographyFromText('SRID=4326;POINT(%f %f)'),            %d          )        } % [longitude, latitude, distance_in_meters])      }      scope :dist, -> {           where(%{            ST_Distance(                ST_GeographyFromText(                  'SRID=4326;POINT(' || vendors.longitude || ' ' ||                    vendors.latitude || ')'                ),                ST_GeographyFromText('SRID=4326;POINT(-76.000000                 39.000000)'),              ) as distance;          } % )       }  end  

however When I call

Vendor.close_to(39.000000, -76.000000).dist   

It does not gives me the distance for the four rows and in fact throws a syntax error. I am a novice rails and postgres developer. I believe I have got the concept entirely wrong. Pleas help me rectify it, how do I find the nearby vendors from a given co-ordinates within a specific range as well as find the distance between each of these near by vendors from the given co-ordinates

DateTimePicker Ruby On Rails

Posted: 21 Jul 2016 05:53 AM PDT

I am trying to add a datetimepicker to rails..... These are the instructions http://xdsoft.net/jqplugins/datetimepicker/


So I have downloaded /jquery.datetimepicker.css and added it to my stylesheets folder…and downloaded jquery.js and /build/jquery.datetimepicker.full.min.js and added them to my javascripts folder….

In the page where I want the datetimepicker to display I have added jQuery('#field').datetimepicker(); and also I included links to files in folders... `

`

Do you know what im doing wrong???

Thanks….

Barry

getting httparty undefined method `code' for #<Hash:0x007ff3625a4800> in rspec

Posted: 21 Jul 2016 07:55 AM PDT

I am very new to rspec and writing specs for my first gem. But i am stuck with this weird error.

code for my rspec is

describe '#success' do      let(:resp) { {"TwilioResponse"=>{"SMSMessage"=>{"Sid"=>"0d1c0cbfb2b5e8f97dddb4479bdbbc6a", "AccountSid"=>"exotel_sid", "From"=>"/exotel_sid", "To"=>"1234", "DateCreated"=>"2016-07-18 15:35:29", "DateUpdated"=>"2016-07-18 15:35:29", "DateSent"=>nil, "Body"=>"test sms", "Direction"=>"outbound-api", "Uri"=>"/v1/Accounts/exotel_sid/Sms/Messages/0d1c0cbfb2b5e8f97dddb4479bdbbc6a", "ApiVersion"=>nil, "Price"=>nil, "Status"=>"queued"}}} }      before{ allow(Generator::Exotel).to receive(:post).with("/#{Generator::configuration.sid}/Sms/send",         {:body => {:To => 1234, :Body => 'test sms'},:basic_auth=>{:username=>"#{Generator::configuration.sid}", :password=>"#{Generator::configuration.token}"}}).and_return(resp) }        it 'returns response object' do          response = Generator::Exotel.send(:to => 1234, :body => "test sms")        expect(response).to eq ({"Status"=>200, "Message"=>"Success"})      end    end  

when i run rspec i am getting this error

NoMethodError:         undefined method `code' for #<Hash:0x007ff3625a4800>  

This is where my response.code is being called

def handle_response(response)    response_base = response['TwilioResponse']    if response_base.include?('RestException')      response_base['RestException']    else      {"Status" => response.code, "Message" => "Success" }    end  end  

I know httparty creates a response object for request and returns response code. But i am not getting how do i create a dummy response_code so that my test case pass. It's nearly 2 days since i am stuck here. Anyone help please. I am really new to ruby and for first time writing spec. Any help will be appreciated.

Update - result for response.inspect

> Generator::Exotel.send(:to => 9030435595, :body => 'jsdhgjkdfg')

it returns following response

> #<HTTParty::Response:0x7fb8c02f93d0 parsed_response={"TwilioResponse"=>{"SMSMessage"=>{"Sid"=>"d6ee0650072c82941ad2f06746d14ab4", "AccountSid"=>"sinscary", "From"=>"/sinscary", "To"=>"9030435595", "DateCreated"=>"2016-07-21 19:56:07", "DateUpdated"=>"2016-07-21 19:56:07", "DateSent"=>nil, "Body"=>"jsdhgjkdfg", "Direction"=>"outbound-api", "Uri"=>"/v1/Accounts/sinscary/Sms/Messages/d6ee0650072c82941ad2f06746d14ab4", "ApiVersion"=>nil, "Price"=>nil, "Status"=>"queued"}}}, @response=#<Net::HTTPOK 200 OK readbody=true>, @headers={"content-type"=>["application/xml"], "date"=>["Thu, 21 Jul 2016 14:26:07 GMT"], "server"=>["Apache/2.2.29 (Amazon)"], "x-powered-by"=>["PHP/5.3.28"], "content-length"=>["542"], "connection"=>["Close"]}>

Jenkins + Ruby on Rails build bash script

Posted: 21 Jul 2016 05:38 AM PDT

Help please, how to make visible ruby-manager such as rvm or rbenv in jenkins user if I already install it on my user. It is necessary to switch ruby version from 1.9 (default) to 2.3.1, as it is required by ruby gems?

Rails merge two query results and then query again

Posted: 21 Jul 2016 06:06 AM PDT

Suppose, I have two query like

users = User.where("name =?", 'john')  active_johns = users.where("active =?", true)  

Now I have to combine the results of the two query and then perform another query on result as below

users = users + active_johns  users = users.where("role = ?", 'admin')  

This does not work and I get error

NoMethodError (undefined method `where' )  

So how can I combine both results and then perform another where query on the result?

Edit

I really need to add the results of two queries. My situation is a bit complicated and I can not use single query for the two queries

users = User.where("name =?", 'john')  active_johns = users.where("active =?", true)  

Then I need to add the results of the two query and then query again.

Most efficient way of comparing arrays with hashes inside them based on a unique hash key in Ruby

Posted: 21 Jul 2016 05:56 AM PDT

I got two hashes hash_a and hash_b which are actually arrays but have hash inside them. Those hash have unique key.

hash_a = [  {:unique_key => 1, :data => 'data for A1'},  {:unique_key => 2, :data => 'data for A2'},  {:unique_key => 3, :data => 'data for A3'}  ]    hash_b = [  {:unique_key => 1, :data => 'data for B1'},  {:unique_key => 2, :data => 'data for B2'},  {:unique_key => 4, :data => 'data for B4'},  {:unique_key => 5, :data => 'data for B5'}  ]  

Now I want to find out difference between hash_a and hash_b, such that I get the hash_c as array of new hashes present in hash_b. I basically want hash_b - hash_a

So I want this output for hash_c, hash_c should be this:

[  {:unique_key => 1, :data => 'data for A1'},  {:unique_key => 2, :data => 'data for A2'},  {:unique_key => 3, :data => 'data for A3'},  {:unique_key => 4, :data => 'data for B4'},  {:unique_key => 5, :data => 'data for B5'}  ]  

I have tried something like this:

hash_c = hash_a  hash_b.each do |inner_bhash|      found = 0        hash_a.each do |inner_ahash|          if(inner_ahash[:unique_key] == inner_bhash[:unique_key])              found = 1              break          end      end        if(found==0)          hash_c.push(inner_bhash)      end  end  

This is doing the trick, but I want a better way. Like hashmap or something, I don't know what.


In addition, I may want to see only the new entries, i.e.

[    {:unique_key => 4, :data => 'data for B4'},    {:unique_key => 5, :data => 'data for B5'}  ]  

I can do that in my code by replacing

hash_c = hash_a  

with

hash_c = []  

but how could I adapt this requirement in the same way?

Rails, is there a way to assosciate a name with each locale?

Posted: 21 Jul 2016 05:53 AM PDT

I have 2 languages at the moment English and Greek (:en & :el).

I'm using the globalize gem.

Is there a way so I can put them in a loop and then extract the name of each language?

For example is there something like the following:

I18n.locale.Name_of_the_locale  

If yes, where do I declare/change it?

How to get number of records by matching a string

Posted: 21 Jul 2016 06:11 AM PDT

I have a service model with 3 keywords. And, i have a sales model counting the number of services served to clients. I am trying to make a statistical report and what i want to ask what is the best way to get the number of services sold by service?

For example, I have service A which was sold 10 times, service B which was sold 20 times etc. How do i get these values easily and programmatically?

I do not want to go individually and search the sales model for each instance of service.

What is the best way to go about it?

class Sale < ApplicationRecord      has_many :sale_services    has_many :services, :through => :sale_services    end    class Service < ApplicationRecord    has_many :sale_services    has_many :sales, through: :sale_services  end    class SaleService < ApplicationRecord    belongs_to :sale, optional: true    belongs_to :service, optional: true  end  

each service has a price, and each sale has a total_price attribute depending on the number of services sold in that particular sale.

Issue with delays in Passenger/nginx

Posted: 21 Jul 2016 04:51 AM PDT

I have a Rails application that is run by Phusion Passenger Standalone (where nginx is built-in). I've enabled the access log both in nginx and in my Rails application. I've seen requests where the access log from nginx reports the request taking, for example, 10 seconds, while the access log from Rails reports it takes less than a second.

In the nginx access log I'm including, among other things, the following variables: $request_time, $connection_requests, $connections_active, $connections_reading, $connections_writing and $connections_waiting. As far as I understand, $connections_active is the number of requests currently in nginx, regardless if they're currently being processed by nginx or the Rails application. If the value of $connections_active is greater than the number of Passenger workers, there's a queue in nginx. The thing is that this value is never greater than the number of workers. I don't see why nginx would not forward the request to an available worker.

This issue is quite hard to consistently reproduce, there doesn't seem to be a pattern on when this occurs. It occurs, most of the time, on the most frequently used request paths, but I assume that's because they're the most frequently used.

Is there a way to get out some more information from Passenger/nginx on why the requests are stuck/delayed? Or any other ideas how to solve this.

Please let me know if there's any more information that is needed.

how to show products under the categories on rails

Posted: 21 Jul 2016 06:20 AM PDT

am working on a rails app and on the show page for a category, i want to show all the products found under that category here is how my

show in category is

def show      @products = Category.friendly.where(params[:name])    end  

and in my views i have it like this

<% @products.each do |product| %>    <%= link_to product_path(id: product.slug, category_name: product.category.name), class: "card" do %>  <div class="product-image">  <%= image_tag product.productpic.url if product.productpic? %>  </div>      <div class="product-text">      <h2 class="product-title"> <%= product.name %></h2>        <h3 class="product-price">£<%= product.price %></h3>    </div>        <% end %>  <% end %>  

here is my products model

class Product < ApplicationRecord    belongs_to :category    mount_uploader :productpic, ProductpicUploader     has_many :order_items  acts_as_taggable  extend FriendlyId  friendly_id :name, use: [:slugged, :finders]   default_scope { where(active: true) }  end  

and my category like this

class Category < ApplicationRecord    has_many :products    extend FriendlyId   friendly_id :name, use: [:slugged, :finders]  end  

what am i doing wrong here?

Braintree form submit button is disabled even after fixing Drop in UI errors

Posted: 21 Jul 2016 04:27 AM PDT

I'm using Braintree Drop in UI, and it seems it has some bug. When there is an error in the payment fields(e.g. credit card number is blank), the containing form submit button gets disabled, which is OK, however if I fixed these error(e.g. by entering a valid value for credit card), the submit button is still disabled. So am I doing something wrong here ?

My code is simple(using Ruby on Rails ? & HAML)

%script{"src" => "https://js.braintreegateway.com/js/braintree-2.27.0.min.js"}    :javascript      $(document).ready(function(){        braintree.setup(MY_TOKEN, "dropin", {          container: $("#payment-form"),          defaultFirst: true        });      })  

undefined method 'id_tag' for ActiveRecord_Associations_CollectionProxy

Posted: 21 Jul 2016 05:54 AM PDT

In my CrawlProduct class I want to get the id_tag from the table ProductInfo:

class CrawlProduct < ActiveRecord::Base      belongs_to :crawl_link        css_id = self.crawl_link.domain.product_infos.id_tag  end  

The table CrawlProducts has a foreign key crawl_link and the table CrawlLinks has a foreign key domain which comes from the table Domain of course. And ProductInfo belongs to domain.

class CrawlProduct < ActiveRecord::Base          belongs_to :crawl_link   end       class CrawlLink < ActiveRecord::Base          belongs_to :domain          has_one :crawl_product  end    class Domain < ActiveRecord::Base          has_many :crawl_links          has_many :product_infos  end    class ProductInfo < ActiveRecord::Base          belongs_to :domain  end  

But at the end, I always receive the following error:

undefined method `id_tag' for #<ProductInfo::ActiveRecord_Associations_CollectionProxy:0x0055d72e423640>  

How can I access the id_tag? There is no column missing as far as I know.

Edit: after the answers I get a different error.

NameError: undefined local variable or method `id_tag' for #<CrawlProduct:0x0055d72fcd9fe0>  

I don't know why I'm getting this problem. Here is how I create the id_tag:

class Domain < ActiveRecord::Base     domain = Domain.create(domain: 'https://www.example.com')     product_info = ProductInfo.create(domain: domain, id_tag: 'some content')  end  

Error with form_for, each and fields_for combined

Posted: 21 Jul 2016 06:43 AM PDT

I am attempting to create a table which contains a form of data to be edited. However, I am receiving the following error:

syntax error, unexpected ')' at line 73  

Line 73 is %tr.medium. I understand this is not where the problem and I assume it's the fields_for line, but am not sure why this is causing a problem as I based it off a similar example online.

= form_for :campaign do    - @campaigns.each do |campaign|      = fields_for "campaign[]", campaign do |campaign_fields|      %tr.medium        %td= link_to campaign.name        %td= campaign.status            %td          -if ["New", "Updated"].include? campaign.status             = campaign_fields.check_box :status, {id: "#{campaign.id}", :class => "approvedservices"}, "Approved", ""        %td{:style => "width:100px;"}          -unless ["Rejected", "Approved"].include? campaign.status            = campaign_fields.check_box :status, {id: "reject#{campaign.id}", :class => "rejectedservices"}, "Rejected", ""        %td.notes{:style => "display: none"}          = campaign_fields.text_field :notes, class: 'form-control mandatory', type: "input"        %tr.medium          %td.white{:colspan => 8}          %td.white{:style => "width:100px;"}            = campaign_fields.submit "Approve", :name => 'Commit'          %td.white{:style => "width:100px;"}            = campaign_fields.submit "Reject", :name => 'Reject'  

Any suggestions?

what's the difference between by passing a symbol and string in where clause with joins

Posted: 21 Jul 2016 04:41 AM PDT

I have two models User and Book. User have username and email field, Book have author and title field. When I am using joins to get the users based on associated data with conditions passed in where clause, I am getting different results

  1. When I run this

    User.joins(:books).where('author = ? ','xxxx')  

Mysql query generated is :

 "SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE (author = 'xxxxx' )"  

gives me the user whose book include xxxx author whereas

  1. When I run this

    User.joins(:books).where(author: 'xxxx')    

Mysql query generated is:

"SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE `users`.`author` = 'xxxx'">   

gives Mysql2::Error: Unknown column 'users.author' in 'where clause':

 SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE `users`.`author` = 'xxxx'   

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'users.author' in 'where clause': SELECT users.* FROM users INNER JOIN book ON book.user_id = users.id WHERE users.author = 'Dan Brown'

My question : is when I am passing a string encapsulated field and value in where clause it gives me result but when I pass a symbol in where clause it gives me mysql unknown column error. So how does ruby interpreter know from where to fetch data in symbol passing and string passing

Devise Omniauth facebook redirect flash message error

Posted: 21 Jul 2016 06:03 AM PDT

I created a rails app with Devise and omniauth to have the fb signup. Everything is working but when I had the redirect to the last page after sign up I have the error on the flash message for the user coming from fb.

here is my application_controller

def set_redirect_path    @redirect_path = request.path  end    def after_sign_in_path_for(resource)    if params[:redirect_to].present?      store_location_for(resource, params[:redirect_to])    elsif request.referer == new_session_url(:user)      super    else      request.env['omniauth.origin'] || stored_location_for(resource) || request.referer || root_path    end  end  

and here the omniauth_callbacks_controller

def facebook      @user = User.from_omniauth(request.env["omniauth.auth"])            if @user.persisted?          sign_in_and_redirect @user, :event => :authentication          set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?      else          session["devise.facebook_data"] = request.env["omniauth.auth"]          redirect_to new_user_registration_url      end  end    def failure      redirect_to root_path  end  

the flash message I get after the sign up and redirect from facebook is the already_authenticated error one saying "You are already signed in."

Does anyone knows how can I solve this issue

thanks

Couldn't find User without an ID rails error

Posted: 21 Jul 2016 06:01 AM PDT

I am new to rails and i keep getting this error

Couldn't find User without an ID

from:

    class UserController < ApplicationController       def show        @user = User.find(params[:id])       end      end  

this is what i have;

model/user.rb

  class User < ActiveRecord::Base          devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable        validates :name, presence: true        validates :email, presence: true          has_many :listings, dependent: :destroy          has_many :purchasing, class_name: "Transaction", foreign_key: "buyer_id", dependent: :destroy        has_many :sell, class_name: "Transaction", foreign_key: "seller_id", dependent: :destroy            has_many :purchased, class_name: "Archive", foreign_key: "buyer_id", dependent: :destroy        has_many :sales, class_name: "Archive", foreign_key: "seller_id", dependent: :destroy          has_many :selling_rooms, class_name: "Room", foreign_key: "seller_id", dependent: :destroy        has_many :buying_room, class_name: "Room", foreign_key: "buyer_id", dependent: :destroy         def can_buy?(listing_price)        if self.points >= listing_price          true        else          false        end       end         def withdraw(listing_price)        self.points -= listing_price       end          def purchasing_list       purchasing.includes(:seller, :listing)      end        def purchased_list       purchased.includes(:seller, :listing)      end        def sell_list       sell.includes(:seller, :listing)      end        def sales_list       sales.includes(:seller, :listing)      end    end  

resources

    resources :users  

I looked around but all i could find was something saying that it is looking for a resource that doesn't exist.

Rails Admin Creating and Using Custom Views

Posted: 21 Jul 2016 04:06 AM PDT

Is there any option for creating a Custom view in Rails Admin ?

I tried to find information about, but unsuccessfully.

No comments:

Post a Comment