Tuesday, June 7, 2016

Rails query: Group by one column and Order by sum of another column | Fixed issues

Rails query: Group by one column and Order by sum of another column | Fixed issues


Rails query: Group by one column and Order by sum of another column

Posted: 07 Jun 2016 07:02 AM PDT

I have a model PurchaseHistory. It has a column user_id and another column is amount. When any user purchased anything it stores the user_id and amount of purchase.

user_id  amount  1        10  2        20  1        20  

Now I want to make a query that will group by user_id and order by the total sum of amount of that user.

So, in this case the query should return something like this

[{1 => 30}, {2 => 20}]   

Restructuring a rails project to support API versioning – what to do with concerns?

Posted: 07 Jun 2016 06:55 AM PDT

I've reorganised a rails project into API modules, where previously the files list inside the controllers folder was flat:

|- controllers/  |-- api/  |--- v0/  |---- authorization_controller.rb  |---- users_controller.rb  |---- ...  |--- v1/  |---- authorization_tokens_controller.rb  |---- users_controller.rb  |---- ...  |-- non_api_controller.rb  |-- ..  

API controllers look like this:

module API::V0    class UsersController      ...    end  end  

After adopting modules for the API, and modules for each respective version, I'm receiving errors when I try to include a concern in one of the classes:

module API::V1    class UsersController      include AuthorizationConcern      ...    end  end  

Currently, authorization_concern.rb is in controllers/api/concerns. But Rails seems to be assuming it's a part of the API::V1 module; the error I get is:

app/controllers/api/v1/users_controller.rb:3:in `<class:AuthorizationTokensController>': uninitialized constant API::V1::AuthorizationTokensController::AuthorizationConcern (NameError)  

It feels like the concern should not be tied to a specific API version – should it? If so, should I put it inside the v1 folder and scope it to the module? If not, what's the syntax for including a concern inside a module class that itself is not part of any module?

Data scraping multiple page clicks loops

Posted: 07 Jun 2016 06:52 AM PDT

Trying to figure out a way to use one mechanise to scrape and add to arrays all of the data we want from the UCAS website. Currently we're struggling with coding in the link clicks for mechanise. Wondering if anyone can help, there are three successive link clicks amidst loops to progress through all search result pages. The first link to display all courses for university is within div class morecourseslink

the second link to display course names, duration and qual is in div class coursenamearea

the third link is in div coursedetailsshowable and the a id is coursedetailtab_entryreqs

currently we are scraping uninames with the below:

class PagesController < ApplicationController    def home      require 'mechanize'  mechanize = Mechanize.new    @uninames_array = []       page = mechanize.get('http://search.ucas.com/search/providers?CountryCode=3&RegionCode=&Lat=&Lng=&Feather=&Vac=2&Query=&ProviderQuery=&AcpId=&Location=scotland&IsFeatherProcessed=True&SubjectCode=&AvailableIn=2016')      page.search('li.result h3').each do |h3|    name = h3.text    @uninames_array.push(name)  end    while next_page_link = page.at('.pager a[text()=">"]')    page = mechanize.get(next_page_link['href'])      page.search('li.result h3').each do |h3|      name = h3.text      @uninames_array.push(name)    end  end    puts @uninames_array.to_s    end  end  

And course names duration and qualification from the below:

require 'mechanize'      mechanize = Mechanize.new  @duration_array = []  @qual_array = []  @courses_array = []    page = mechanize.get('http://search.ucas.com/search/results?Vac=2&AvailableIn=2016&IsFeatherProcessed=True&page=1&providerids=41')      page.search('div.courseinfoduration').each do |x|  puts x.text.strip  page.search('div.courseinfooutcome').each do |y|  puts y.text.strip    end    while next_page_link = page.at('.pager a[text()=">"]')    page = mechanize.get(next_page_link['href'])    page.search('div.courseinfoduration').each do |x|      name = x      @duration_array.push(name)      puts x.text.strip    end  end  while next_page_link = page.at('.pager a[text()=">"]')    page = mechanize.get(next_page_link['href'])    page.search('div.courseinfooutcome').each do |y|      name = y      @qual_array.push(name)      puts y.text.strip    end  end  page.search('div.coursenamearea h4').each do |h4|  puts h4.text.strip    end    while next_page_link = page.at('.pager a[text()=">"]')    page = mechanize.get(next_page_link['href'])    page.search('div.coursenamearea h4').each do |h4|      name = h4.text      @courses_array.push(name)      puts h4.text.strip    end  end  end  

Javascript only loads after refresh (Ruby on rails - Materialize CSS)

Posted: 07 Jun 2016 07:02 AM PDT

I'm using a Ruby on Rails application in combination with Materialize CSS.

The dropdown of links in the navigation works on the dashboard, but on any other page you have to refresh it first. Same for the Wave effect on buttons and tabs. I already tried 20 or so solutions , but they didn't work.

I also have a javascript for a multistep form that isn't linked to Materialize CSS. It's used in a script tag on the specific page.

 $(document).ready(function () {      // get all items      var navListItems = $('div.setup-panel div a'),          allParts = $('.setup-content'),          allNextBtn = $('.nextBtn'),          allPrevBtn = $('.prevBtn');        allParts.hide();        navListItems.click(function (e) {        e.preventDefault();        var $target = $($(this).attr('href')),            $item = $(this);        // hide when disabled        if (!$item.hasClass('disabled')) {          navListItems.removeClass('btn-primary').addClass('btn-default');          $item.addClass('btn-primary');          allParts.hide();          $target.show();          $target.find('input:eq(0)').focus();        }      });      // previous      allPrevBtn.click(function(){        var curStep = $(this).closest(".setup-content"),            curStepBtn = curStep.attr("id"),            prevStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().prev().children("a");          prevStepWizard.removeAttr('disabled').trigger('click');      });      //next      allNextBtn.click(function(){        //setup next part        var curStep = $(this).closest(".setup-content"),            curStepBtn = curStep.attr("id"),            nextStep = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),            curInputs = curStep.find("input[type='text']"),            curRadios = curStep.find("input[type='radio']"),            curChecks =curStep.find("input[type='checkbox']"),            isValid = true;          if (curStep.hasClass('step1')){          var txt = "";          if (document.getElementById("snapshot_name").value == null || document.getElementById("snapshot_name").value == "") {            txt = "You need to fill in a snapshot name";            document.getElementById("error1").innerHTML = txt;          }else{            document.getElementById("error1").innerHTML = txt;            goToNext(nextStep)          }        } else if (curStep.hasClass('step2')){          var txt2 = "";          var counter = 0;          var counterQ1 = 0;          var counterQ2 = 0;          for(var i=0; i<curRadios.length; i++){            if (curRadios[i].checked){              counter++            }          }          for(var i=0; i<curChecks.length; i++){            if (curChecks[i].checked){              var name = curChecks[i].id;              if (name.search(/Q1/i)){                counterQ1++              }else {                counterQ2 ++              }              }          }            if (counter == (1) && counterQ1 > 0 && counterQ2 > 0){            document.getElementById("error2").innerHTML = txt2;            goToNext(nextStep)          } else{            txt2 = "You need to fill in all questions"            document.getElementById("error2").innerHTML = txt2;          }        }        else if (curStep.hasClass('step3')){          var txt3 = "";          var counter = 0;          var counterQ1 = 0;          var counterQ2 = 0;          for(var i=0; i<curRadios.length; i++){            if (curRadios[i].checked){              counter++            }          }            if (counter == (5) ){            document.getElementById("error3").innerHTML = txt3;            goToNext(nextStep)          } else{            txt3 = "You need to fill in all questions"            document.getElementById("error3").innerHTML = txt3;          }        }          else if (curStep.hasClass('step6')){          var txt6 = "";          var counter = 0;          for(var i=0; i<curRadios.length; i++){            if (curRadios[i].checked){              counter++            }          }            if (counter == (14) ){            document.getElementById("error6").innerHTML = txt6;            goToNext(nextStep)          } else{            txt6 = "You need to fill in all questions"            document.getElementById("error6").innerHTML = txt6;          }        }        else {          goToNext(nextStep)        }        });        $('div.setup-panel div a.btn-primary').trigger('click');    });      function goToNext(nextStep){        nextStep.removeAttr('disabled').trigger('click');        nextStep.removeClass('disabled').trigger('click');    }  

Anyone have an idea what kind of solution I can try?

NSDateFormatter converting rails string to NSDate returns nil?

Posted: 07 Jun 2016 06:44 AM PDT

I'm trying to convert a datetime passed from a rails api into an NSDate object so I can style it. I'm using NSDateFormatter and here is what I'm currently trying, I keep getting nil returned though, I've looked at some of the existing answers from other questions and adjusted but haven't been able to get it to work yet.

My code is as follows:

NSString *dateStr = @"2016-06-06 10:45:13 UTC";    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];  [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];  NSDate *date = [dateFormat dateFromString:dateStr];  

Rails timeout when exporting to csv with Draper

Posted: 07 Jun 2016 06:33 AM PDT

I'm using Draper and my export is based on fields that come from the decorator not from the model.

It's taking around 9 seconds to get the values of each row.

I have the following relations:

model1 has many model2  model2 has many model3  model3 has one model4  model4 has many model5  

How can I enhance it ?

Querying a nested array of hashes for existence of a key in jsonb postgres with activerecord

Posted: 07 Jun 2016 06:26 AM PDT

I'm using the jsonb datatype in postgres to store various variable settings for a model.

With hashes it seems pretty straightforward.

If I create:

Model.create(settings:{a:"b", c:"d"})  Model.where("settings -> 'a' ? 'b'") #or  => Model...  Model.where("settings -> 'c' ? 'd'") #or if I just want to check the keys  => Model...  Model.where("settings ? 'a'")  => Model...  

If I do something a little more complex with mutiple keys:

Model.create(settings:{a:{b:"c", d:"e"}})    Model.where("settings -> 'a' ? 'b' ") #or  => Model...  Model.where("settings -> 'a' ? 'd' ")  => Model...  

does likewise

Now if I put an array at the top level, I can do the following:

Model.create(settings:["a","b"])  Model.where("settings ? "a")  => Model...  

and get the object returned.

And with a nested array.

Model.create(settings:{a:["a","b"]})  Model.where("settings -> 'a' ? 'a'")  => Model...  Model.where("settigns -> 'a' ? :v", v: 'a')  => Model...  

But as soon as I put anything more complex in that array I can't seem to get a match anymore.

Model.create(settings:[{a:"b"}, {c:"d"}])  Model.where("settings ? :v", v: {a:"b"})  => []  Model.create(settings:{a:[{b:"c"}, {d:"e"}]})  Model.where("settings -> 'a' ? :v", v: {b:"c"})  => []  

all fail to return the object.

I'd like to get to the point where I can query the elements of a nested array for whether they have certain keys in their contained hashes, but I can't get around this issue. I'm obviously missing something syntactically, but I can't work out what it is.

Can't get Heroku not to precompile

Posted: 07 Jun 2016 06:24 AM PDT

I'm using Rails::API 4.2. When I try to deploy to Heroku, I see

remote: -----> Preparing app for Rails asset pipeline  

even though I've taken a number of steps that I understood would disable asset precompilation in production.

I've tried commenting out all the asset-related stuff in config/environments/production.rb.

I've tried adding config.assets.enabled = false to config/environments/production.rb.

I've tried adding a blank manifest.json at config/assets/manifest.json and then adding config.assets.manifest = Rails.root.join('config', 'assets', 'manifest.json') to config/environments/production.rb.

Why is Heroku still trying to precompile my assets?

Rails - seeding with paperclip images

Posted: 07 Jun 2016 06:44 AM PDT

I found several questions on that topic and I followed the instructions to seed my models with images. However, when seeding I get an error "PG::UndefinedColumn: ERROR: column meals.meal_avatar does not exist" even though my model has it. This is my Meal model

class Meal < ActiveRecord::Base    has_attached_file :meal_avatar, styles: { large: '300x300' }, default_url: '/images/:style/missing.png'    validates_attachment_content_type :meal_avatar, content_type: /\Aimage\/.*\Z/  end  

This is the migration

  def self.up      change_table :meals do |t|        t.attachment :meal_avatar      end    end  

The allowed parameters in the controller

  def meal_params      params.require(:meal).permit(:name, :meal_avatar)    end  

The way I seed the image(It is out of context but you can get the idea)

meal_seed = [    {      name: "Salad",      meal_avatar: File.new("app/assets/images/salad.jpg")    }  ]  meal_seed.each do |meal_params|    meal = category.meals.find_or_create_by(meal_params)  end  

Any idea why my seeds fail :? Thank you!

Data scraping multiple array creation and ordering

Posted: 07 Jun 2016 06:01 AM PDT

We're trying to scrape the course names, qualification and duration of the course and store each in a separate array. With the below we pull all of that, but it seems to be in random order, with some parts potentially ordered by page etc. Wondering if anybody is able to help.

require 'mechanize'      mechanize = Mechanize.new  @duration_array = []  @qual_array = []  @courses_array = []    page = mechanize.get('http://search.ucas.com/search/results?Vac=2&AvailableIn=2016&IsFeatherProcessed=True&page=1&providerids=41')      page.search('div.courseinfoduration').each do |x|  puts x.text.strip  page.search('div.courseinfooutcome').each do |y|  puts y.text.strip    end    while next_page_link = page.at('.pager a[text()=">"]')    page = mechanize.get(next_page_link['href'])    page.search('div.courseinfoduration').each do |x|      name = x      @duration_array.push(name)      puts x.text.strip    end  end  while next_page_link = page.at('.pager a[text()=">"]')    page = mechanize.get(next_page_link['href'])    page.search('div.courseinfooutcome').each do |y|      name = y      @qual_array.push(name)      puts y.text.strip    end  end  page.search('div.coursenamearea h4').each do |h4|  puts h4.text.strip    end    while next_page_link = page.at('.pager a[text()=">"]')    page = mechanize.get(next_page_link['href'])    page.search('div.coursenamearea h4').each do |h4|      name = h4.text      @courses_array.push(name)      puts h4.text.strip    end  end  end  

Adding path to autoload works - why?

Posted: 07 Jun 2016 05:59 AM PDT

I'm working on the front-end for our web app which is constructed using Angular.

The backend is a rails app with a modification to allow it to act as an API as well as a normal Rails application (pre-existing application here so it makes a-lot of sense to keep it)

I'm using JWT's on the front-end to validate a user but I also issue a refresh_token so they can get a new JWT after a certain amount of time. The code looks like this:

def delegation    user = User.user_from_refresh_token params[:refresh_token]    render json: {jwt: user.generate_auth_token}  end  

This is setup as a POST in the route file:

post  "auth/delegation"  

So the line in question is this one:

user = User.user_from_refresh_token params[:refresh_token]  

which would mean you'd expect the user.rb model to contain a method called user_from_refresh_token which I do:

def self.user_from_refresh_token token      refresh_token = RefreshToken.find_by!(token: token)      raise API::Unauthorized.new("This refresh token has been revoked") if refresh_token.revoked?      find(refresh_token.user_id)    end  

But the error that I get when I call this is:

NoMethodError: undefined method `user_from_refresh_token' for User  

Question 1 - How come I can't call this like it is? Shouldn't this just work?

Note: I fixed this issue by modifying the autoloader to add this in:

config.autoload_paths += %W(#{config.root}/lib #{config.root}/model/concerns)  

Question 2 - Why does this have to be done in order for the previous part to work?

rails: how to silence a single warning in a method

Posted: 07 Jun 2016 05:56 AM PDT

How can I turn off this warning:

DEPRECATION WARNING: superclass_delegating_accessor is deprecated and will be removed from Rails 5.0 (use class_attribute instead). (called from block in at /home/ubuntu/myapp/config/environments/development.rb:84)

I get a whole bunch of these. I am running a rake "task/job" like this:

rails runner "Tickets.new('foo').perform"  

Rails, is there a way to give a file_field an image by default?

Posted: 07 Jun 2016 07:01 AM PDT

I have an edit form for my articles.

Every article has an image.

I have Current Image and Change Image sections.

Here is my code:

<%=form_for @article, url: articles_update_path,remote: true, html: {class: "form-horizontal"} do |f|%>    <fieldset class="content-group">    <legend class="text-bold">Images</legend>    <div class="form-group">      <label class="col-lg-2 text-semibold">Current image:</label>      <div class="col-lg-10">        <%= image_tag @article.image_url(:thumb) unless @article.image.blank?%>      </div>    </div>    <div class="form-group">      <label class="col-lg-2 text-semibold">Change image:</label>      <div class="col-lg-10">        <%= f.file_field :image, :class => 'file-input-custom', 'data-show-caption' => true, 'data-show-upload' => false, :accept => 'image/*'%>      </div>    </div>  </fieldset>    <% end %>  

Now the thing is that if the user chooses to edit the article and does not give an image again, there is no image.

I want to make my edit form so that if someone does not pick an image, the image that the article already has is saved.

Is that possible?

How can I cache a button click on rails?

Posted: 07 Jun 2016 05:55 AM PDT

I would like to save in local cache when a user clicks a certain button. Basically a message shows up and the user clicks a button to not show the message again. I was thinking that the best way to achieve this is by saving that the user clicked the button in the local cache. How would I go about doing this? If you have a better way to achieve this functionality please let me know.

Use Ransack to do a generic search on all Fields

Posted: 07 Jun 2016 05:44 AM PDT

I am using Ransack to search a Users model, from a generic search box. I would like this field to do a generic search on all fields in the model. I could manually write out a long query parameter for ransack:

first_name_or_last_name_or_email_or_job_title_or .... _cont_any: "query string"  

But maintaining this would be a pain, and it would be rigidly tied to the current model structure.Instead I am trying to dynamically build the symbol that will be the key to be passed to ransack. I have to deal with foreign keys and exclude some fields from the returned symbol, since they need not be searched. Here is my attempt (in the User Model):

# build a ransack symbol to search all fields  def self.all_columns_search_query      # specific forms to append in search query for foreign keys    foreign_keys_search_fields = {      "location_id" => "location_name",      "county_id" => "county_name"    }      # search fields to be excluded in search    excluded_cols = ["id"]      query = ""    column_names.each do |c|      next if excluded_cols.include? c        # append the corresponding search field if it is a foreign key      # else just append the field itself      query << foreign_keys_search_fields.fetch(c, c)      query << "_or_"    end      query.chomp!("_or_")    query << "_cont_any"    query.to_sym  end  

This upon inspection, this appears to be a correct symbol:

User.all_columns_search_query  => :first_name_or_last_name_or_designation_or_gender_or_date_of_birth_or_current_field_or_employment_or_education_or_mobile_or_signup_date_or_created_at_or_updated_at_or_email_or_county_name_or_year_of_graduation_or_location_name_cont  

However, when I attempt to use this with ransack as follows, it returns all the users.

User.ransack(all_columns_search_query => "specificuser@example.com").result  

The SQL generated seems fine, though I am not experienced enough in SQL to spot an error:

User.ransack(all_columns_search_query => "specificuser@example.com").result.to_sql  => SELECT "users".* FROM "users" LEFT OUTER JOIN "counties" ON "counties"."id" = "users"."county_id" LEFT OUTER JOIN "locations" ON "locations"."id" = "users"."location_id" WHERE ((((((((((((((("users"."first_name" LIKE '%specificuser@example.com%' OR "users"."last_name" LIKE '%specificuser@example.com%') OR "users"."designation" LIKE '%specificuser@example.com%') OR "users"."gender" LIKE '%specificuser@example.com%') OR "users"."date_of_birth" LIKE '%%') OR "users"."current_field" LIKE '%specificuser@example.com%') OR "users"."employment" LIKE '%specificuser@example.com%') OR "users"."education" LIKE '%specificuser@example.com%') OR "users"."mobile" LIKE '%specificuser@example.com%') OR "users"."signup_date" LIKE '%%') OR "users"."created_at" LIKE '%%') OR "users"."updated_at" LIKE '%%') OR "users"."email" LIKE '%specificuser@example.com%') OR "counties"."name" LIKE '%specificuser@example.com%') OR "users"."year_of_graduation" LIKE 0) OR "locations"."name" LIKE '%specificuser@example.com%')  

I have a feeling in my gut that it might be because of the different data-types eg attempting to search a date field using a string, Ransack just flips and silently fails, defaulting to User.all.

Can anyone on here perhaps confirm my suspicions or otherwise shed some light?

EDIT

This seems to be working sometimes as I play around with excluded fields and search queries.

After installing rails with ansible, i get this error and dont know what to do

Posted: 07 Jun 2016 05:25 AM PDT

After Installing rails with ansible into Ubuntu 14.04/trusty and logged in the virtual environment, I simple ran 'rails s' to start a project but I get this error below. I have no idea what to do. Can anyone please tell me how to solve this problem? What are these programs? Do I really need those to use rails command?

The program 'rails' can be found in the following packages: * ruby-railties-3.2 * ruby-railties-4.0 Ask your administrator to install one of them

My rails ansible code is below...

---  - name: install rails  gem: >  name=rails  state=latest  executable=~/.rbenv/shims/gem  tags:      - rails  

two column belong to association with diferent name rails

Posted: 07 Jun 2016 05:44 AM PDT

I Have a result table with winner and loser column, these are related with the user table:

   #Result controller     @results = Result.includes(:user).all.paginate(page: params[:page], per_page: 20)       #result model     class Result < ActiveRecord::Base       belongs_to :user     end       #user model     class User < ActiveRecord::Base       has_many :result     end  

how i do to make this posible?

   <td><%= result.user.winner %></td>     <td><%= result.user.loser %></td>  

bundle install doesn't succeed

Posted: 07 Jun 2016 06:57 AM PDT

I'm currently helping this rails project. (I just started ruby, even programming, so please go easy on me...) when I tried to bundle install with project shared Gemfile/Gemfile.lock, it causes some fuss with json 1.8.1 and libv8 3.16.14.3 install.

I hit some search result and half of the answers involved bundle update, which is, according to much more experience team member, a taboo when working in a team because it brings a chaos to project Gemfile.lock.

I tried the other half with different things like El-Captain related Recovery mode bit or gem update -system or libv8 related things. It seems any of those didn't work.

Then again, it's highly possible I didn't use precise inquiry to search for the answers, since I am a beginner and don't have much knowledge or guess about what's usually causing issue or 'this is base library so i should get this done right.' or stuff like that.

If someone could help me, that would be great kindness. I'm going to leave the log here:

Installing json 1.8.1 with native extensions  Gem::Ext::BuildError: ERROR: Failed to build gem native extension.    current directory: /usr/local/lib/ruby/gems/2.3.0/gems/json-    1.8.1/ext/json/ext/generator  /usr/local/opt/ruby/bin/ruby -r ./siteconf20160607-22004-lr43ei.rb extconf.rb  creating Makefile    current directory: /usr/local/lib/ruby/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator  make "DESTDIR=" clean    current directory: /usr/local/lib/ruby/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator  make "DESTDIR="  compiling generator.c  In file included from generator.c:1:  ./../fbuffer/fbuffer.h:175:47: error: too few arguments provided to function-like macro invocation      VALUE result = rb_str_new(FBUFFER_PAIR(fb));                                                ^  /usr/local/Cellar/ruby/2.3.1/include/ruby-2.3.0/ruby/intern.h:797:9: note: macro 'rb_str_new' defined here    #define rb_str_new(str, len) __extension__ (    \          ^  In file included from generator.c:1:  ./../fbuffer/fbuffer.h:175:11: warning: incompatible pointer to integer conversion initializing 'VALUE' (aka 'unsigned long') with an expression of type 'VALUE (const char *, long)' (aka 'unsigned long (const char *, long)') [-Wint-conversion]      VALUE result = rb_str_new(FBUFFER_PAIR(fb));            ^        ~~~~~~~~~~  1 warning and 1 error generated.  make: *** [generator.o] Error 1    make failed, exit code 2    Gem files will remain installed in /usr/local/lib/ruby/gems/2.3.0/gems/json-1.8.1 for inspection.  Results logged to /usr/local/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-15/2.3.0/json-1.8.1/gem_make.out  Installing libv8 3.16.14.3 with native extensions    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        current directory: /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/ext/libv8  /usr/local/opt/ruby/bin/ruby -r ./siteconf20160607-22004-1gr1tzk.rb extconf.rb  creating Makefile  Compiling v8 for x64  Using python 2.7.10  Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1  Using compiler: /usr/bin/g++  Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1  ../src/cached-powers.cc:136:18: error: unused variable 'kCachedPowersLength' [-Werror,-Wunused-const-variable]  static const int kCachedPowersLength = ARRAY_SIZE(kCachedPowers);                   ^  1 error generated.  make[1]: *** [/usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/cached-powers.o] Error 1  make: *** [x64.release] Error 2  /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/ext/libv8/location.rb:36:in `block in verify_installation!': libv8 did not install properly, expected binary v8 archive '/usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/tools/gyp/libv8_base.a'to exist, but it was not found (Libv8::Location::Vendor::ArchiveNotFound)      from /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `each'      from /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `verify_installation!'      from /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/ext/libv8/location.rb:26:in `install!'      from extconf.rb:7:in `<main>'  GYP_GENERATORS=make \      build/gyp/gyp --generator-output="out" build/all.gyp \                    -Ibuild/standalone.gypi --depth=. \                    -Dv8_target_arch=x64 \                    -S.x64  -Dv8_enable_backtrace=1 -Dv8_can_use_vfp2_instructions=true -Darm_fpu=vfpv2 -Dv8_can_use_vfp3_instructions=true -Darm_fpu=vfpv3    CXX(target) /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/allocation.o    CXX(target) /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/atomicops_internals_x86_gcc.o    CXX(target) /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum.o    CXX(target) /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum-dtoa.o    CXX(target) /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/cached-powers.o    extconf failed, exit code 1    Gem files will remain installed in /usr/local/lib/ruby/gems/2.3.0/gems/libv8-3.16.14.3 for inspection.  Results logged to /usr/local/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-15/2.3.0/libv8-3.16.14.3/gem_make.out  

I'm so sorry guys, I'm using Mac!

Request FB posts after a given post id using FbGrapb2 ruby gem

Posted: 07 Jun 2016 05:05 AM PDT

Is there any other way to get facebook posts after a particular post id using FBGraph2 gem in rails

Is there a rails gem for products and shopping cart?

Posted: 07 Jun 2016 05:32 AM PDT

I've found some gems like spree commerce but that's too complex for what I need.

I only need system of products and a shopping cart (without payments) to implement within current rails app. Is there any gem that does this?

How to add translation for document

Posted: 07 Jun 2016 04:55 AM PDT

I have a table called 'documents' which has attachment (by paperclip gem), and I want to add translation for this attachment (by globalize gem) to be used in Activeadmin. So once I open the document page in the active admin, I would like to add two or more translations of the document but for the same model (same model id but only locales changes).

The schema create table DB table of Document model is:

create_table "documents", force: :cascade do |t|      t.datetime "created_at",       null: false      t.datetime "updated_at",       null: false      t.string   "doc_file_name"      t.string   "doc_content_type"      t.integer  "doc_file_size"      t.datetime "doc_updated_at"      t.integer  "model_id"    end  

and the database is postgres.

Rails : Analytics/Reporting Tool

Posted: 07 Jun 2016 05:47 AM PDT

I have an application with reporting feature where user can go query for my data. As of now, I have written all the code to create the dynamic queries based on user's criteria and then run those queries in the data base and show it to the user.

What I need is a reporting tool, to which I will just give my data/database , and it will be provide an interface to run reports on.

My application is a Ruby on Rails application.

Any ideas ?

issue with render json for array

Posted: 07 Jun 2016 04:24 AM PDT

I have this array coming from my server. Which is returned like this when i use puts:

formatted_total_price  &Acirc;&pound;66.00  formatted_total_price  &Acirc;&pound;128.00  formatted_total_price  &Acirc;&pound;246.00  formatted_total_price  &Acirc;&pound;243.20  formatted_total_price  &Acirc;&pound;242.86  formatted_total_price  &Acirc;&pound;242.50  

so i just tried to do this:

price1.each do |price11|    price11.json {render json: price11.as_json}  end  

However this returns this error:

NoMethodError (undefined method `json' for ["formatted_total_price", "&Acirc;&pound;66.00"]:Array):  

What I'm wanting is to have the formatted_total_price and the &Acirc;&pound;66.00 to match up to look like this:

"formatted_total_price":"&Acirc;&pound;66.00"  

Heres the actual code i have:

doc.xpath("//script[@type='text/javascript']/text()").each do |text|         if text.content =~ /more_options_on_polling/           price1 = text.to_s.scan(/\"(formatted_total_price)\":\"(.+?)\"/).uniq           description = text.to_s.scan(/\"(ticket_desc)\":\"(.+?)\"/).uniq           price = price1 + description           price1.each do |price11|             price11.json {render json: price11.as_json}           end         end  

Cannot run puma server for my application because of bcrypt

Posted: 07 Jun 2016 04:22 AM PDT

My machine is a Windows 8 32 bit machine and I have ruby 2.1.8.

I am facing a problem when I am trying to open my app in puma and rails server. I am even unable to run bundle install. The erorr is:

in `require': 126: The specified module could not be found.    - C:/Ruby21/lib/ruby/gems/2.1.0/gems/bcrypt-ruby-3.1.1.rc1-x86-mingw32/lib/bcrypt_ext.so (LoadError)  

and the bundle install error is:

could not find gem 'bcrypt (=3.1.5 rc1) x64-mingw32' in any of the gemfile ruby 2.1.8  

same problem happens also for bcrypt version 3.0.0 and 3.1.1 also

My Gemfile is:

source 'http://rubygems.org'    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.1.9'    # Use sqlite3 as the database for Active Record  gem 'pg'    gem 'plivo'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 4.0.0'    # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'    # Use CoffeeScript for .js.coffee assets and views  gem 'coffee-rails', '~> 4.0.0'  gem 'coffee-script-source', '1.8.0'    # See https://github.com/sstephenson/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library gem 'jquery-rails'    gem 'rails-jquery-autocomplete', :git 'https://github.com/AyushRuiaHW/rails-jquery-autocomplete.git'    # 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', '~> 1.2'    group :doc do  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', require: false   end    gem 'tzinfo-data'  gem 'faraday'  gem 'hypdf', '~> 1.0.12'  gem 'currency-in-words'  gem "jquery-ui-rails"  gem 'Instamojo-rb'  gem "kaminari"  gem "rails-erd"  gem 'levenshtein', '~> 0.2.2'  gem "lol_dba"  gem "bullet", :group => "development"  gem "bootstrap-sass"  gem 'rack-mini-profiler'  gem 'newrelic_rpm'  gem 'puma_worker_killer'  # Use ActiveModel has_secure_password  # gem 'bcrypt-ruby', '~> 3.0.0'    # Use unicorn as the app server  # gem 'unicorn'    # Use Capistrano for deployment  # gem 'capistrano', group: :development    # Use debugger  # gem 'debugger', group: [:development, :test]    gem 'postmark-rails'  gem 'bcrypt-ruby', '3.1.5.rc1', :require => 'bcrypt'  gem 'puma'  gem "paperclip", "~> 3.0"  gem 'aws-sdk', '~> 1'  gem 'aws-sdk-resources', '~> 2'  gem 'rails_12factor', group: :production    ruby "2.1.8"  

Nomethoderror on form using mail_form gem for second form

Posted: 07 Jun 2016 04:28 AM PDT

i am building a website for which i already made a working contact form using the mail_form gem. But now i wan't to create another form somewhere on the website, also using the mail_form gem.

I made a new controller, a new model, new views and put up the routes.

boosts_controller.rb

class BoostsController < ApplicationController        def new        @contact = Contact.new      end        def create        @contact  = Contact.new(params[:boost])        @contact.request = request        if @contact.deliver          flash.now[:notice] = "Thank you very much, we will contact you on your email with further instructions"        else          flash.now[:error]  = "Something went wrong, please try again."          render :new        end      end    end  

Model: boost.rb

class Boost < MailForm::Base    attribute :paypal_transaction_reference,   :validate => true    attribute :email,                          :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i    attribute :message    attribute :account_name,                   :validate => true    attribute :account_password,               :validate => true    attribute :account_password_confirmation,  :validate => true    attribute :nickname,                       :captcha  => true      # Declare the e-mail headers. It accepts anything the mail method    # in ActionMailer accepts.    def headers      {          :subject => "Form",          :to => "xxxx@hotmail.com, xxxx@gmail.com",          :from => %("#{account_name}", <#{email}>)      }    end  end  

boosts/new.html.erb

<div class="col-md-12 text-center">    <div class="sign-box">      <header class="sign-title"> form</header>        <%= form_for @boost do |f| %>            <div class="field form-group">            <%= f.label :paypal_transaction_reference, class: 'float-left' %>            <%= f.text_field :paypal_transaction_reference, required: true, class: 'form-control', autofocus: true %>          </div>            <div class="field form-group">            <%= f.label :email, class: 'float-left' %>            <%= f.email_field :email, class: 'form-control', required: true, autocomplete: "off" %>          </div>            <div class="field form-group">            <%= f.label :account_name, class: 'float-left' %>            <%= f.text_field :account_name, class: 'form-control', required: true,  autocomplete: "off" %>          </div>            <div class="field form-group">            <%= f.label :account_password, class: 'float-left' %>            <%= f.password_field :account_password, class: 'form-control',required: true, autocomplete: "off" %>          </div>            <div class="field form-group">            <%= f.label :account_password_confirmation, class: 'float-left' %>            <%= f.password_field :account_password_confirmation, class: 'form-control', required: true,  autocomplete: "off" %>          </div>            <div class="field form-group">            <%= f.label :message, class: 'float-left' %>            <%= f.text_area :message, as: :text, class: 'form-control', autocomplete: "off" %>          </div>            <div class="hidden">            <%= f.label :nickname %>            <%= f.text_field :nickname, hint: 'leave this field blank' %>          </div>              <%= f.submit 'Send', class: 'btn btn-rounded' %>      <% end %>    </div>  </div>  

routes.rb from the working contact form plus the new one.

  match '/boosts', to: 'boosts#new', via: 'get'    resources :boosts,   only: [:new, :create]      match '/contacts', to: 'contacts#new', via: 'get'    resources :contacts, only: [:new, :create]  

The error i get on localhost is:

undefined method `paypal_transaction_reference' for #<Contact:0x007f9dbbb307d0>  

The error log

Completed 500 Internal Server Error in 31ms (ActiveRecord: 0.0ms)    ActionView::Template::Error (undefined method `paypal_transaction_reference' for #<Contact:0x007f9dbbb307d0>):       6:        7:         <div class="field form-group">       8:           <%= f.label :paypal_transaction_reference, class: 'float-left' %>       9:           <%= f.text_field :paypal_transaction_reference, required: true, class: 'form-control', autofocus: true %>      10:         </div>      11:       12:         <div class="field form-group">    app/views/boosts/new.html.erb:9:in `block in _app_views_boosts_new_html_erb___4155220419788953995_70157717804640'    app/views/boosts/new.html.erb:5:in `_app_views_boosts_new_html_erb___4155220419788953995_70157717804640'  

Where to put @user.skip_confirmation! in devise signup

Posted: 07 Jun 2016 03:36 AM PDT

I want to skip confirmation email in signup and want to send manually. To skip I will do

@user.skip_confirmation!

But where to write this line?

POST request done with Authenticity Token, but exception still rased

Posted: 07 Jun 2016 02:47 AM PDT

My controller is responding to a js GET request, and in my js.erb file I am reporting back with the Fingerprint2 generated browser data of the users browser. This is done with a POST request, because of the large data string, so I have inserted a beforeSend method that adds the Authenticity Token.

However, this is rejected with ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken. When I check, the header looks like it does in the GET requests that succeed:

X-CSRF-Token:hl/TgkY7k0yBG03KX9IBrsDhk2K4tUUh8JTooT7A0yYZ0l53p8lTt0F3dZvRwyS3bIkbbkuTdElP2KisozjXjw==  

The js code looks like this:

(new Fingerprint2).get(function(fingerprint, components) {    return $.ajax({      url: "/user_browser",      type: "post",      beforeSend: function(xhr) {        xhr.setRequestHeader('X-CSRF-Token',        $('meta[name="csrf-token"]').attr('content'))      },      data: {        some_id: '123',        components: JSON.stringify(components),        fingerprint: fingerprint      },      dataType: "json"    }).success(function(data) {});  });  

How to get rails image location in javascript file

Posted: 07 Jun 2016 03:18 AM PDT

I have an image in app/assets/images/ folder which is named map-marker.png. I need to get the image location in my javascript file to use it as a map marker.

 var image  = "map-marker.png";      var beachMarker = new google.maps.Marker({          position: myLatLng,          map: map,          icon: image      });  

Redirecting after clicking on the date datetimepicker rails

Posted: 07 Jun 2016 02:29 AM PDT

Redirecting after clicking on the date. I redirect only after selecting a date subsequent izmenneniya hands and remove the focus from the field. So I can not hide the field input in css. How to change the code after clicking on the date when sending the form?

html.erb:

<%= form_tag :action => 'method_name' do %>    <%= text_field_tag('datetimepicker12', nil, options = { :onchange => "this.form.submit()"}) %>    <% end %>  

js:

 $(function () {          $('#datetimepicker12').datetimepicker({              format: 'DD-MM-YYYY',              inline: true,              locale: 'ru',              useCurrent: false          });      });  

Thank you!

How to render this array into usable json

Posted: 07 Jun 2016 02:22 AM PDT

So i have this coming back from my webscrape

formatted_total_price  &Acirc;&pound;66.00  formatted_total_price  &Acirc;&pound;128.00  formatted_total_price  &Acirc;&pound;246.00  formatted_total_price  &Acirc;&pound;243.20  formatted_total_price  &Acirc;&pound;242.86  formatted_total_price  &Acirc;&pound;242.50  

Heres the code for this:

   if text.content =~ /more_options_on_polling/       price1 = text.to_s.scan(/\"(formatted_(?:total_price))\":\"(.+?)\"/).uniq       puts price1     end  

How would i go about making this into json so that i can append just the price to a table?

Thanks Sam

No comments:

Post a Comment