Friday, November 25, 2016

Struggling to understand why joins/includes are needed with Rails when an association exists in the model | Fixed issues

Struggling to understand why joins/includes are needed with Rails when an association exists in the model | Fixed issues


Struggling to understand why joins/includes are needed with Rails when an association exists in the model

Posted: 25 Nov 2016 07:59 AM PST

I am trying to create a very complicated query and am having troubles with it - so I'm going back to the basics to try and figure out what I'm missing. I've been reading the Rails Guides for Active Record Associations and Active Record Query Interface (specifically section 12 - joins) and I'm failing to understand how they are related and why joins/includes are needed.

The Associations page says "With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models." Section 12.2 of the Query page says "Active Record lets you use the names of the associations defined on the model as a shortcut for specifying JOIN clauses for those associations when using the joins method."

These two statements seem somewhat at odds with each other to me. If I create as belongs_to association why do I need a join if I'm trying to pull data from both tables? Looking at it another way:

class Customer < ActiveRecord::Base    has_many :orders  end    class Order < ActiveRecord::Base    belongs_to :customer  end  

If I do @orders = Order.all I can output the customer name by doing @orders.first.customer.name. However, if I want to select all orders with 'smith' in the name I would do something like @orders=Order.where('customer.name ilike "%smith%"').joins(:customer)

How is it that this "relationship" is working in first half, but requires the join in the second half?

Mailchimp does not forget about unsubscribed users

Posted: 25 Nov 2016 07:55 AM PST

I'm having a problem when it comes to unsubrscibe email from my mailchimp list.

Basically I have a user with an email. When the user subscribe to my service I automatically insert his email into my mailchimp list through the gem gibbon (the server is Ruby on Rails v2.2.3)

 @@gibbon = Gibbon::Request.new(api_key: ENV['MAILCHIMP_API_KEY'])   @@list = 'list_id'   ...   @@gibbon.lists(@@list).members.create(body: {email_address: email, status: "subscribed", merge_fields: {FNAME: first_name, LNAME: full_name}})  

After creating the account the user can obviously change his email address. If he does so, I add the new email to the mailchimp list and I delete the old one:

begin    @@gibbon.lists(@@list).members.create(body: {email_address: email, status: "subscribed", merge_fields: {FNAME: first_name, LNAME: full_name}})  rescue => e    render :json => {      :error => true,      :message => "Email already present",      :user => u,      :personal_link => u.current_link    }      return  end    member = @@mailchimp.lists(@@list).members(u.email)  member.update status: "unsubscribed"  

This works fine in most cases. The problem comes when I try to change my email with my old one:

0) Subscribe to the website with the email "test@gmail.com"

Works fine.

1) From my account I change my email from "test@gmail.com" to "test1@gmail.com"

Works fine, I don't see anymore my old email in the mailchimp list and I see the new one.

2) Change back my email from "test1@gmail.com" to "test@gmail.com"

Mailchimp throws this error:

#<Gibbon::MailChimpError: the server responded with status 400 @title="Member Exists", @detail="test@gmail.com is already a list member.  

The problem is that I don't have any user with this email in the database and I don' have any user with that email in my mailchimp list. It' like mailchimp does not forget about unsubribed user and prevents me to add the same user twice in a list, even if it has been cancelled before.

How can I solve the problem?

Show view for different Users types

Posted: 25 Nov 2016 07:57 AM PST

I am planning an application with a User model + different User subtypes (such as Students, Teachers, ...) with a dedicated model for each. I am planning to authenticate on Users level directly in rails, with no specific gem.

My problem is about handling the Users Show view file:

  • should I show the users directly in the Show file of the User controller (adding a lot of conditions in my view file, depending of the User subtype) or
  • should I use the User show controller action as a gateway redirecting the a controller dedicated to each subtype, ...then having a more straightforward show view.

Get profile image Linkedin in Rails

Posted: 25 Nov 2016 07:58 AM PST

I have seen that some apps show the photo of the users or customers. I want to do the same with a CRM we are doing. We want to add the image of the contacts in the CRM: I understand these apps are getting these images from somewhere... Where are these apps getting the images of their customers from? Gravatar? Linkedin? Any other place. IF you let me know, I would really appreciate. Thanks

see rails updated objects from params hash

Posted: 25 Nov 2016 07:23 AM PST

I would like to see all updated, changed objects that were updated from params hash, like so: current_user.events.update(params[:events].keys,params[:events].values)

This updates all rows correctly, but I would like to get ids of all updated objects, and only these, so I can use them in Jquery to highlight only changed ones. This is how params looks like:

Parameters: {"utf8"=>"✓", "events"=>{"334"=>{"name"=>"44232"}, "342"=>{"name"=>"1-2"}}}

Compile and deploy ruby on VSTS

Posted: 25 Nov 2016 07:45 AM PST

Now a days the word DevOps has become a buzzword in software development practices. So I thought of rubbing this concept to ruby. For this I've fire up a VM on azure. With Ubuntu 16, Installed ruby 2.2.5 and rails 5.x.x.x. Pushed the code on to VSTS git.

Now I want to build it using hosted build agent through SSH task for build and deployment.

So kindly throw some light on how to proceed here.

Thanks in advance.

Heroku docker deployment

Posted: 25 Nov 2016 07:04 AM PST

I was following the this article https://devcenter.heroku.com/articles/container-registry-and-runtime and I'm stuck with "heroku container:push". I run "heroku container:push --app mediabox" and the docker image is properly build and then it start to push it to registry and this is what I get:

Successfully built 7926b98d51b5 The push refers to a repository [registry.heroku.com/mediabox/web] 38d48dd6de30: Preparing 969058e6ddc9: Preparing 2f454953e0e7: Preparing f67c1ecd32a1: Preparing 44fade3982ca: Preparing 0accb1c81980: Waiting e79bbdfaa0d3: Waiting 1be5d1797b73: Waiting 5c0a4f4b3a35: Waiting 011b303988d2: Waiting error parsing HTTP 400 response body: unexpected end of JSON input: "" ! Error: docker push exited with 1

This is my Dockerfile: FROM ruby:2.3.1-alpine

RUN apk --update --no-cache add build-base less libxml2-dev libxslt-dev nodejs postgresql-dev && mkdir -p /app

WORKDIR /app

COPY Gemfile Gemfile.lock ./

RUN gem install bundler

RUN bundle

COPY . ./

CMD ["script/docker-entrypoint.sh"]

I can't find the solution here. Thanks for your help.

Weird rounding issue

Posted: 25 Nov 2016 07:02 AM PST

Something very weird is happening with decimals and floating numbers and I can't understand why or where (ruby/rails/postgresql).

Given a purchases table with a decimal column - total:

p1 = Purchase.where(total: 5.99).first_or_create  p2 = Purchase.where(total: 5.99).first_or_create    [p1.id, p2.id] # => [1, 2]    p3 = Purchase.where(total: 5.99.to_d).first_or_create  p4 = Purchase.where(total: 5.99.to_d).first_or_create    [p3.id, p4.id] # => [1, 1]  

Both Ruby and postgresql have no problem representing 5.99 exactly, no matter if decimals or floats:

5.99.to_s         # => "5.99"  5.99.to_d.to_s    # => "5.99"  5.99 == 5.99.to_d # => true    SELECT CAST(5.99 AS DECIMAL) AS decimal, CAST(5.99 AS FLOAT) AS float;    #  decimal | float     # ---------+-------    #     5.99 |  5.99    # (1 row)    SELECT CAST(5.99 AS DECIMAL) = CAST(5.99 AS FLOAT) AS equal;    #  equal     # -------    #  t    # (1 row)  

To top it all off, this doesn't happen with some other values:

p5 = Purchase.where(total: 5.75).first_or_create  p6 = Purchase.where(total: 5.75).first_or_create  p7 = Purchase.where(total: 5.75.to_d).first_or_create    [p5.id, p6.id, p7.id] # => [3, 3, 3]  

Reset forgotten password - best way [on hold]

Posted: 25 Nov 2016 07:18 AM PST

My goal seems to be very common. I need best way to reset forgotten user password via email. There is one problem. That's API so we don't consider any views for users to reset their password. I've been thinking about two solutions:

User makes HTTP POST to let's say host/password/recover passing email in body. API sends email message to given email address and now:

  1. Email contains new generated password and link to confirm that password
  2. Email contains question link to reset password and then API sends second email with randomly generated password and link to confirm that password (optional) or password just has been changed.
  3. Email contains special token which is required to send next HTTP POST e.g to host/password/reset with body like:

    {    "token": "fnh24ry218fhi3n34f34",    "password": "qwe123qwe",    "password_confirmation": "qwe123qwe"  }  

And after check token correctness password will be changed.

I just given three possible solutions but to be honest I don't like any of them. Maybe there is a better and clearer way to do it?

I need only general idea or flow. I don't need any chunks of code. That issue suits to any programming language.

No route matches [POST] "/collections/1/photos/new"

Posted: 25 Nov 2016 07:04 AM PST

Can somebody help me with this error?

I just started a basic Rails project where i have Collections. Every Collection can have multiple Photos.

However, it is possible for me to create those Collections. But whenenver I want to create a Photo attached to a Collection i get this error:

No route matches [POST] "/collections/1/photos/new"  

routes.rb

Rails.application.routes.draw do        resources :collections do      resources :photos    end  end  

collection_controller.rb

class CollectionsController < ApplicationController    before_action :set_collection, only: [:show, :edit, :update, :destroy]      # GET /collections    # GET /collections.json    def index      @collections = Collection.all    end      # GET /collections/1    # GET /collections/1.json    def show    end      # GET /collections/new    def new      @collection = Collection.new    end      # GET /collections/1/edit    def edit    end      # POST /collections    # POST /collections.json    def create      @collection = Collection.new(collection_params)        respond_to do |format|        if @collection.save          format.html { redirect_to @collection, notice: 'Collection was successfully created.' }          format.json { render :show, status: :created, location: @collection }        else          format.html { render :new }          format.json { render json: @collection.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /collections/1    # PATCH/PUT /collections/1.json    def update      respond_to do |format|        if @collection.update(collection_params)          format.html { redirect_to @collection, notice: 'Collection was successfully updated.' }          format.json { render :show, status: :ok, location: @collection }        else          format.html { render :edit }          format.json { render json: @collection.errors, status: :unprocessable_entity }        end      end    end      # DELETE /collections/1    # DELETE /collections/1.json    def destroy      @collection.destroy      respond_to do |format|        format.html { redirect_to collections_url, notice: 'Collection was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_collection        @collection = Collection.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def collection_params        params.require(:collection).permit(:name, :description)      end  end  

photos_controller.rb

class PhotosController < ApplicationController    before_action :set_photo, only: [:show, :edit, :update, :destroy]      # GET /photos    # GET /photos.json    def index      @photos = Photo.all    end      # GET /photos/1    # GET /photos/1.json    def show    end      # GET /photos/new    def new      @photo = Photo.new    end      # GET /photos/1/edit    def edit    end      # POST /photos    # POST /photos.json    def create      @photo = Photo.new(photo_params)        respond_to do |format|        if @photo.save          redirect_to @photo          format.html { redirect_to @photo, notice: 'Photo was successfully created.' }          format.json { render :show, status: :created, location: @photo }        else          format.html { render :new }          format.json { render json: @photo.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /photos/1    # PATCH/PUT /photos/1.json    def update      respond_to do |format|        if @photo.update(photo_params)          format.html { redirect_to @photo, notice: 'Photo was successfully updated.' }          format.json { render :show, status: :ok, location: @photo }        else          format.html { render :edit }          format.json { render json: @photo.errors, status: :unprocessable_entity }        end      end    end      # DELETE /photos/1    # DELETE /photos/1.json    def destroy      @photo.destroy      respond_to do |format|        format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_photo        @photo = Photo.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def photo_params        params.require(:photo).permit(:name, :collection_id)      end  end  

photos/new.html.erb

<h1>New Photo</h1>    <%= render 'form', photo: @photo %>    <%= link_to 'Back', collection_photos_path %>  

photos/_form.html.erb

<%= form_for [@collection, @photo], url: new_collection_photo_path do |f| %>    <% if photo.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(photo.errors.count, "error") %> prohibited this photo from being saved:</h2>          <ul>          <% photo.errors.full_messages.each do |message| %>            <li><%= message %></li>          <% end %>        </ul>      </div>    <% end %>      <p>Naam:</p>    <%= f.text_field :name %>      <div class="actions">      <%= f.submit %>    </div>  <% end %>  

ActionCable - Failed to upgrade to WebSocket in production

Posted: 25 Nov 2016 06:10 AM PST

ActionCable doesn't work in production. Works well in development, but not in production.

Running Nginx with Puma on Ubuntu 14.04. I have checked that redis-server is up and running.

Rails -v 5.0.0.1

production.log:

INFO -- : Started GET "/cable/"[non-WebSocket] for 178.213.184.193 at 2016-11-25 14:55:39 +0100  ERROR -- : Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE: )  INFO -- : Finished "/cable/"[non-WebSocket] for 178.213.184.193 at 2016-11-25 14:55:39 +0100  

Request from client:

GET ws://mityakoval.com/cable HTTP/1.1  Host: mityakoval.com  Connection: Upgrade  Pragma: no-cache  Cache-Control: no-cache  Upgrade: websocket  Origin: http://mityakoval.com  Sec-WebSocket-Version: 13  User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36  Accept-Encoding: gzip, deflate, sdch  Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,uk;q=0.2,nb;q=0.2  Cookie: _vaktdagboka_session=******  Sec-WebSocket-Key: *******  Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits  Sec-WebSocket-Protocol: actioncable-v1-json, actioncable-unsupported  

Response:

HTTP/1.1 404 Not Found  Server: nginx/1.4.6 (Ubuntu)  Date: Fri, 25 Nov 2016 13:52:21 GMT  Content-Type: text/plain  Transfer-Encoding: chunked  Connection: keep-alive  Cache-Control: no-cache  X-Request-Id: d6374238-69ef-476e-8fc5-e2f8bbb663de  X-Runtime: 0.002500  

nginx.conf:

upstream puma {    server unix:///home/mityakoval/apps/vaktdagboka/shared/tmp/sockets/vaktdagboka-puma.sock;  }    server {    listen 80 default_server deferred;    # server_name example.com;      root /home/mityakoval/apps/vaktdagboka/current/public;    access_log /home/mityakoval/apps/vaktdagboka/current/log/nginx.access.log;    error_log /home/mityakoval/apps/vaktdagboka/current/log/nginx.error.log info;      location ^~ /assets/ {      gzip_static on;      expires max;      add_header Cache-Control public;    }      try_files $uri/index.html $uri @puma;    location @puma {      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header Host $http_host;      proxy_redirect off;        proxy_pass http://puma;    }      location /cable {      proxy_pass http://puma;      proxy_http_version 1.1;      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header Host $http_host;      proxy_set_header Upgrade $http_upgrade;      proxy_set_header Connection "Upgrade";    }      error_page 500 502 503 504 /500.html;    client_max_body_size 10M;    keepalive_timeout 10;  }  

cable.yml:

redis: &redis    adapter: redis    url: redis://127.0.0.1:6379    production: *redis    development:    adapter: async    test:    adapter: async  

in production.rb:

config.action_cable.allowed_request_origins = ["http://mityakoval.com"]  

in routes.rb:

mount ActionCable.server, at: '/cable'  

Dynamically create rows and columns in bootstrap / rails

Posted: 25 Nov 2016 06:46 AM PST

Using Rails with bootstrap I'm trying to layout a page which will have an unknown number of blocks of content on it. On small screens there should be 1 column, on medium screens 2 columns, and on larger screens 3 columns.

Such as...

enter image description here

However I can't work out how to slice up the content so it works reliably. Currently I have this in my view :

<div class="container">    <% @posts.each_slice(3)  do |posts| %>      <div class="row">      <% posts.each  do |post| %>        <div class="col-sm-6 col-lg-4">          <img src="<%= post.image %>" class="img-responsive">          <h2><%= post.title %></h2>          <h6><%= post.created_at.strftime('%b %d, %Y') %></h6>          <p> <%= raw(post.body).truncate(358) %></p>        </div>      <% end %>      </div>    <% end %>  </div>  

But this produces...

enter image description here

I've tried changing the each_slice(3) and class="col-sm-6 col-lg-4" however regardless of the combinations I choose one of the medium or large views breaks.

How do I reliably achieve the desired effect above regardless of the number of items on the page?

My Rails Console keeps crashing

Posted: 25 Nov 2016 06:07 AM PST

I have a problem with my Rails Console, it keeps crashing and I can't figure out why. For example, when I type the following

rails c  Category.connection  

It begins with the following error:

/Users/****/.rvm/gems/ruby-2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/sqlite3_adapter.rb:27: [BUG] Segmentation fault at 0x00000000000110  ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15]  

Then it gives the a whole lot of error messages, with more than 1500 lines with my gemsfiles listed.

I hope someone can help me to fix this problem, by the way I am using macOS Sierra 10.12.1

When anyone needs additional information, please let me know because I don't know what I should include for someone to recognize the problem.

Add assets to pipeline from engine without require it in main application.js

Posted: 25 Nov 2016 05:46 AM PST

I need to add assets to pipeline from moutable engine (JS and CSS) but i can't require it in application.js.

Main app: main_app/app/assets/application.js

Engine: my_engine/app/assets/my_engine/application.js

How i can get this to work ?

Sometimes "Incomplete response received from application " error message appear

Posted: 25 Nov 2016 05:14 AM PST

I'm using apache2 +passenger+ mysql, I got a welcome page, but when I was refresh page sometimes " Incomplete response received from application" appear. Why? And how to fix it.

Devise registration for with nested entity

Posted: 25 Nov 2016 05:36 AM PST

I'm building a Rails app where User can have more Addresses.

User has_many :addresses  Address belong_to :user  

I'm using Devise for authentication. I want an User entity and first Address entity to be created by one form when the user is registering.

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>    <%= f.email_field :email %><br />    <%= t.password_field :password %><br />      <%= f.fields_for resource.addresses do |a| %>      <%= a.text_field :street %>    <% end %>  <% end %>  

But I'm getting

undefined method 'street' for ActiveRecord::Associations::CollectionProxy []

what must be done in controller?

Thanks

Application_helper and ruby gem Redcarpet error

Posted: 25 Nov 2016 05:52 AM PST

I am trying to get the markdown up and running on my webapp using pygment 0.6.3 and redcarpet 3.3. Unfortunately, I am facing a wall here when calling the markdown method:

uninitialized constant ApplicationHelper::Redcarpet

Here is the module I am calling from application_helper.rb:

module ApplicationHelper      def markdown(content)          render = Redcarpet::Render::HTML.new(hard_wrap: true, filter_html: true)          options = {              autolink: true,               no_intra_emphasis: true,              disable_indented_code_blocks: true,              fenced_code_blocks: true,              lax_html_blocks: true,              strikethrough: true,              superscript: true          }          Redcarpet::Markdown.new(renderer, options).render(content).html_safe      end  end  

I am therefore call this method the following way:

<div id= "content">          <%= markdown @post.content%>  </div>  

Among other researches, I already did the following:

  • bundle update
  • bundle install
  • restart my server
  • tried other versions of pygments and redcarpet

I've found some info saying I should remove the Gemfile.lock (when deleting it, it automatically pops up again).

Thank you for your help on this.

Edit: Added Gemfile

source 'https://rubygems.org'    gem 'rails', '~> 5.0.0', '>= 5.0.0.1'  gem 'sqlite3'  gem 'puma', '~> 3.0'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.2'  gem 'jquery-rails'  gem 'turbolinks', '~> 5'  gem 'jbuilder', '~> 2.5'  gem 'pygments.rb', '~> 0.6.3'  gem 'redcarpet', '~> 3.3', '>= 3.3.4'    group :development, :test do    gem 'byebug', platform: :mri  end    group :development do    gem 'web-console'    gem 'listen', '~> 3.0.5'    gem 'spring'    gem 'spring-watcher-listen', '~> 2.0.0'  end    gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  

docker Connection refused

Posted: 25 Nov 2016 05:00 AM PST

I have running docker and when want to send request from docker to my rails server i have got

curl localhost:3000  curl: (7) Failed connect to localhost:3000; Connection refused  

but my rails server has been started.

    docker version  Client:   Version:      1.9.1   API version:  1.21   Go version:   go1.4.3   Git commit:   a34a1d5   Built:        Fri Nov 20 17:56:04 UTC 2015   OS/Arch:      darwin/amd64    Server:   Version:      1.12.3   API version:  1.24   Go version:   go1.6.3   Git commit:   6b644ec   Built:        2016-10-26T23:26:11.105168198+00:00   OS/Arch:      linux/amd64  

i have started docker with eval "$(docker-machine env default)"

Can't connect to local MySQL server through socket in ubuntu while running rails

Posted: 25 Nov 2016 06:34 AM PST

I trying to follow the steps here https://gorails.com/setup/windows/10 to run ruby on rails on linux, everything was fine except when i try to execute this

rake db:create

i got this error,

#<Mysql2::Error: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)>  Couldn't create database for {"adapter"=>"mysql2", "encoding"=>"utf8", "pool"=>5, "username"=>"root", "password"=>"secretpassword", "host"=>"localhost", "database"=>"apps_development"}, {:charset=>"utf8"}  (If you set the charset manually, make sure you have a matching collation)  Created database 'apps_development'  #<Mysql2::Error: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)>  Couldn't create database for {"adapter"=>"mysql2", "encoding"=>"utf8", "pool"=>5, "username"=>"root", "password"=>"secretpassword", "host"=>"localhost", "database"=>"apps_test"}, {:charset=>"utf8"}  (If you set the charset manually, make sure you have a matching collation)  Created database 'apps_test'  

what this means?

How to convert image html code have animation elements to ruby image_tag

Posted: 25 Nov 2016 04:40 AM PST

<img src="assets/stockBroker_photo02.png" alt="" class="animated" data-animation="fadeInRight" data-animation-delay="300">  

I want to convert this code to ruby on rails code meanz in image_tag. I know simple image_tag with class name but these data animation issue is creating. How to add these data-animation in image_tag

Rails axlsx gem - Formula not escaping

Posted: 25 Nov 2016 04:39 AM PST

Is there a way to ignore executing a formula while rendering spreadsheet?

Currently, sheet.add_row("=10+10") will evaluate 20, even if I give :formula => :false or :type=> :string

The only hacky way is to provide a single quote, but it's not a pretty approach.

Login to amazon partnernet using Ruby Mechanize

Posted: 25 Nov 2016 04:08 AM PST

I try to login into amazon partnernet, e.g. https://partnernet.amazon.de/ using the Ruby Mechanize gem:

Gemfile:

# https://github.com/sparklemotion/mechanize  gem 'mechanize'  

The code below is a rake task. It worked in the past, I think Amazon changed the page html so this code is no longer working, e.g. by changing the submit button of the form name="sign_in" to an image type=input.

desc "Cron Task for Email Notifications"  task :email_amazon_stats => :environment do    puts "Start: Fetch and send Amazon Sales from yesterday (#{Time.now})"      # login to Amazon Partnernet    a = Mechanize.new    a.user_agent_alias = 'Mac Safari'    a.follow_meta_refresh = true    a.redirect_ok = true      a.get('https://partnernet.amazon.de/') do |page|      # Submit the login form      page.form_with(:name => 'sign_in') do |f|        username_field = f.field_with(:id => "username")        username_field.value = "email@example.com"        password_field = f.field_with(:id => "password")        password_field.value = "somepassword"      end.submit        start_date  = Time.now - 1.day      end_date    = Time.now      my_page2 = a.get("https://partnernet.amazon.de/gp/associates/network/reports/report.html?ie=UTF8&deviceType=all&endDay=#{(end_date.strftime('%d').to_i).to_s}&endMonth=#{((end_date.strftime('%m').to_i)-1).to_s}&endYear=#{end_date.strftime('%Y').to_i.to_s}&periodType=exact&preSelectedPeriod=monthToDate&program=all&reportType=earningsReport&startDay=#{start_date.strftime('%d').to_i.to_s}&startMonth=#{((start_date.strftime('%m').to_i)-1).to_s}&startYear=#{start_date.strftime('%Y').to_s}")        form = my_page2.form_with(:name => 'htmlReport')      button = form.button_with(:name => 'submit.download_XML')      xml = a.submit(form, button)        # ASIN="3423347570"      # Binding="paperback"      # Category="14"      # Date="December 01, 2015"      # DeviceType="BROWSER"      # EDate="1448928000"      # Earnings="0,65"      # LinkType="asn"      # Price="9,25"      # Qty="1"      # Rate="7,03"      # Revenue="9,25"      # Seller="Amazon.de"      # Tag="yx-21"      # Title="Kopf schl&#228;gt Kapital: Die ganz andere Art, ein Unternehmen zu gr&#252;nden Von der Lust, ein Entrepreneur zu sein (dtv Sachbuch)"/>        doc = Nokogiri::XML(xml.body)      @sales = []      doc.xpath("//Item").each do |item|        @sales << {            :sale_itemasin    => item['ASIN'],            :sale_itemname    => item['Title'].truncate(80),            :sale_date        => Time.at(item['EDate'].to_i).strftime("%Y-%m-%d %H:%M:%S").to_s,            :sale_amount      => '%.2f' % item['Revenue'].gsub(',','.').to_f,            :sale_commission  => '%.2f' % item['Earnings'].gsub(',','.').to_f        }      end        earnings = 0      @sales.each do |s|        earnings += s[:sale_commission].to_f      end      @total_commission = '%.2f' % earnings    end      ReportsMailer.daily_dashboard(@total_commission,@sales).deliver    puts "Done: Fetch and send Amazon Sales from yesterday (#{Time.now})"  end  

Can someone help me in this?

--

I looked for similar questions how to restructure the submit, but so far nothing works. Login is not happening. (Yes, PWD is correct :-) )

Similar question, but does not solve the problem above: Cannot Login to Amazon with Ruby Mechanize

Rspec is not catching error StatementInvalid

Posted: 25 Nov 2016 06:35 AM PST

I'm trying to defend myself from SQL injection, I'm using variable as column name in #where:

class BuildSegment::FindUsers      def initialize(params)      @key = User.connection.quote_column_name(params[:key])      @negative = params[:negative]      @pattern = params[:pattern]    end      def call      if @negative        users = User.where.not("#{@key} LIKE ?", @pattern)      else        users = User.where("#{@key} LIKE ?", @pattern)      end        users.uniq    end  end  

Variable @key is taken from Hash which may be manipulated by user. So, for example if @key = "email LIKE '%' OR email" and I'm passing @key directly to Active Record query, I get:

SELECT "users".* FROM "users" WHERE (email LIKE '%' OR email LIKE '')  

which returns all users. I found quote_column_name(params[:key]) as a solution which returns ActiveRecord::StatementInvalid error:

ActiveRecord::StatementInvalid:         PG::UndefinedColumn: ERROR:  column "email LIKE '%com%' OR email" does not exist         LINE 1: SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%...                                                               ^         : SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%com%' OR email" LIKE '')  

This test, however, is failing:

expect(segment_builder.call).to raise_error(ActiveRecord::StatementError)  

And full backtrace:

Failures:      1) BuildSegment is protected from SQL injection       Failure/Error: users_to_add = users.flatten         ActiveRecord::StatementInvalid:         PG::UndefinedColumn: ERROR:  column "email LIKE '%com%' OR email" does not exist         LINE 1: SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%...                                                               ^         : SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%com%' OR email" LIKE '')       # ./app/services/build_segment.rb:51:in `flatten'       # ./app/services/build_segment.rb:51:in `users_passing_all_rules'       # ./app/services/build_segment.rb:46:in `users_passing_filter'       # ./app/services/build_segment.rb:32:in `block in users_meeting_requirements_for'       # ./app/services/build_segment.rb:31:in `each'       # ./app/services/build_segment.rb:31:in `users_meeting_requirements_for'       # ./app/services/build_segment.rb:8:in `call'       # ./spec/services/build_segment_spec.rb:107:in `block (2 levels) in <top (required)>'       # ------------------       # --- Caused by: ---       # PG::UndefinedColumn:       #   ERROR:  column "email LIKE '%com%' OR email" does not exist       #   LINE 1: SELECT DISTINCT "users".* FROM "users" WHERE ("email LIKE '%...       #                                                         ^       #   ./app/services/build_segment.rb:51:in `flatten'  

Where could be my error?

Query approximate equality

Posted: 25 Nov 2016 07:37 AM PST

Given a decimal column, is there a nice way to query for approximate equality?

You can use ranges:

Purchase.where(total: (value - delta)..(value + delta)).first  

But it looks like a common enough issue that Rails would usually try to solve for you, given that floating numbers can't always be represented exactly.

Reset value of an attribute to default

Posted: 25 Nov 2016 05:36 AM PST

I would like to know how I can set a models attribute and possible associations to its default value.

user = User.find_by(name: "Martin")  user.phone = 012345  user.save!  # some time later  user.phone = # set to default  user.save!  

Thanks

Cloudfront preventing changes to my rails app in production

Posted: 25 Nov 2016 03:46 AM PST

I am attempting to use the Cloudfront CDN for my Rails app.

In production.rb, I set up my Cloudfront Domain Name as the asset host...

config.action_controller.asset_host = "ex1ex1ex1ex1ex1.cloudfront.net"  

Whenever I make a change/git-commit with my Rails assets code, I see those changes implemented immediately while I'm in the development environment.

But, when I switch to production environment ($ rails s -e production), those changes I've just made go away, even after I've added my changes to my public folder's assets folder via $ rake assets:precompile.

But if I comment out config.action_controller.asset_host = "ex1ex1ex1ex1ex1.cloudfront.net", I immediately see those changes I've made to my assets code in my production environment.

If I then deploy my app to Heroku -- and thus to my Cloudfront Distribution's Origin (my app's URL) -- those changes are correctly implemented. But unfortunately Cloudfront is no longer my asset host.

But then, when I go back to production.rb and uncomment config.action_controller.asset_host = "ex1ex1ex1ex1ex1.cloudfront.net", I then DO SEE those changes to my assets code. Then I can re-deploy to Heroku with Cloudfront as my asset host this time.

That is obviously a terrible work-flow.

I see that my Cloudfront Distribution's Origin is my deployed app's URL. So, I'm assuming (whether in localhost or in my online app) that the front-end assets code is "drawing from" my Distribution's most recently updated Origin (my app's URL).

I did attempt to enable CORS in assets per the advice from http://ricostacruz.com/til/rails-and-cloudfront, but to no avail.

I really perplexed as to how I can do regular deploys to Heroku without having to comment out config.action_controller.asset_host = "ex1ex1ex1ex1ex1.cloudfront.net" the first time around. Am I missing something with CORS?

Should I set up http://localhost:3000/ as another Origin for my Distribution so that my Distribution can then "draw from" my localhost immediately? That would seem a bit strange. Or, should I set up a Bucket to "draw from"? If so, how would I get all of my Rails assets (which are constantly changing) into that Bucket dynamically & continually?

How to control the order of joined records in Rails 4

Posted: 25 Nov 2016 04:37 AM PST

Rails 4. Sqlite3 DB (for development).

My model looks like this:

class Group < ActiveRecord::Base    has_many :memberships    has_many :people, through: :memberships    has_many :notes, as: :notable      scope :with_active_members, -> { joins(people: [:role]).where(people: {active: true}).uniq }    end  

And I use it like this:

@groups = Group.with_active_members.order("groups.position")  

The join works perfectly well. But I want to order the people records alphabetically. To be very clear, I don't want to order the groups by their associated people. I want the groups to be ordered by their position field but I want the associated collections of people to be ordered alphabetically. Can this be done with the ORM?

cybersource test transaction for other currencies

Posted: 25 Nov 2016 04:47 AM PST

I am using test account for cybersource to check test transactions using secure acceptance API. It works for USD currency. But when I use GBP, EUR currencies it throws error saying misconfigured paymentech processor with reason code 102.

I see default payment processor used for test transactions is smartpay.

How can I test transactions for GBP transactions? Is there any way to configure payment processor for test account transactions?

I am using secure acceptance api as given in doc: http://apps.cybersource.com/library/documentation/dev_guides/Secure_Acceptance_SOP/Secure_Acceptance_SOP.pdf

I am able to perform USD transactions with test account which uses smartpay processor.

But problem comes for GBP transactions which throws error misconfigured paymentech processor

Test URL submit data here :https://testsecureacceptance.cybersource.com/silent/pay

API request params:

access_key: 'xxx', profile_id: 'xxx', transaction_type: 'sale', locale: 'en', transaction_uuid: 'xxxx', signed_date_time: 'xxx', signed_field_names: 'xxx', unsigned_field_names:'card_type,card_number,card_expiry_date,card_cvn', amount: '10.00', currency: 'GBP', payment_method: 'card'

Response I receive is:

"req_card_number":"xxxxxxxxxxxx0000", "req_locale": "en", "signature": "aj+TrKcIF/p4tY61T0pTu2WWuu7bfCFelYQCMXvOxac=", "req_card_expiry_date": "01-2019", "req_ignore_avs": "true", "req_payment_method": "card", "req_amount": "10.0", "req_currency":"GBP", "req_card_type":"001", "decision":"DECLINE", "message": "Misconfigured paymentech processor", "reason_code": "102"

Reference code I used is: http://apps.cybersource.com/library/documentation/dev_guides/samples/sa_sop/ruby_sop.zip

Permission Denied when creating myapp in ruby on rails

Posted: 25 Nov 2016 02:58 AM PST

As the first time with linux and ruby on rails, I am following this guide, https://gorails.com/setup/windows/10 everthing in the steps works fine except the final step when I tried to execute this command.

rails new myapp -d mysql

after hitting enter I got this message.

/home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/fileutils.rb:253:in `mkdir': Permission denied @ dir_s_mkdir - /myapp (Errno::EACCES)          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/fileutils.rb:253:in `fu_mkdir'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/fileutils.rb:227:in `block (2 levels) in mkdir_p'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/fileutils.rb:225:in `reverse_each'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/fileutils.rb:225:in `block in mkdir_p'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/fileutils.rb:211:in `each'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/fileutils.rb:211:in `mkdir_p'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/empty_directory.rb:50:in `block in invoke!'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/empty_directory.rb:116:in `invoke_with_conflict_check'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/empty_directory.rb:49:in `invoke!'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:94:in `action'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/actions/empty_directory.rb:14:in `empty_directory'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/generators/app_base.rb:153:in `create_root'          from (eval):1:in `create_root'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/command.rb:27:in `run'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:126:in `invoke_command'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `block in invoke_all'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `each'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `map'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `invoke_all'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/group.rb:232:in `dispatch'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.19.1/lib/thor/base.rb:440:in `start'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/application.rb:17:in `<top (required)>'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/cli.rb:14:in `<top (required)>'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:127:in `require'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:127:in `rescue in require'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require'          from /home/fil/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/exe/rails:9:in `<top (required)>'          from /home/fil/.rbenv/versions/2.3.3/bin/rails:22:in `load'          from /home/fil/.rbenv/versions/2.3.3/bin/rails:22:in `<main>'  

What is the problem?, can you suggest a solution?

Rails filtering has and belongs to many databases

Posted: 25 Nov 2016 06:05 AM PST

i have a user table that has and belongs to many tools.

so each user can have as many tools as they want and the tools can be associated with the user.

what i am trying to do is create a filter system so that on my main page people can click a selection of tools and it will show only users that have an association with those tools.

so it needs to brings back only users that have all of the skills someone has selected for instance someone who has Git and Jira , Not git or Jira

i can do it for one tool by using

if params["Confluence"]          contractors = contractors.includes(:tools).where(tools: { name: "Confluence" })  end  

i have tryed doing something like this

contractors = contractors.includes(:tools).where(tools: { name: "Confluence" , name: "Git", name: "JIRA Core" , name:"JIRA Software"})  

but it only brings back the users with the last tool in the list. i have also tryed like this

    if params["JIRA Core"]          contractors = contractors.includes(:tools).where( tools: {name: "JIRA Core"})      end        if params["JIRA Software"]          contractors = contractors.includes(:tools).where( tools: {name: "JIRA Software"})      end  

however this does not work either. anyone have any ideas?

No comments:

Post a Comment