Monday, October 10, 2016

Compressing but keeping same dimensions with Imagmagick | Fixed issues

Compressing but keeping same dimensions with Imagmagick | Fixed issues


Compressing but keeping same dimensions with Imagmagick

Posted: 10 Oct 2016 07:48 AM PDT

I have a model handling images uploadeded with paperclip and processed with imagemagick.

Here is the model code :

has_attached_file :image, styles: { big: "2000x2000", small: "1000x1000", thumb: "250x250"}  validates_attachment :image, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }  

I use all those different styles but I also use the original style. Though the original size may be very big, some pictures are above 15 Mo.

I would like to compress the original style yet not knowing exactly what size it is, sometimes image is cropped and the 3:2 ratio is not respected.

I found this thread : Reducing the file size of a very large images, without changing the image dimensions yet not adapted to Rails environment.

Sanitizing a Stored Procedure Call in SQL Statement

Posted: 10 Oct 2016 07:41 AM PDT

I'm working in Rails and ActiveRecord, and am attempting to sanitize a SQL statement that executes a stored procedure:

query =<<-SQL      SELECT *      FROM #{stored_procedure_name}      (          #{param_1},          #{param_2}      )  SQL  

From what I understand, the stored procedure should be sanitized at the database layer because of parametrization (due to the way I defined the function). However, how can I sanitize the query above? I tried ActiveRecord's sanitize methods to no avail by using something like

statement =<<-SQL      SELECT * FROM ? (?, ?)  SQL  

and then passing the parameters in, but this didn't work - and seems silly.

Rails Each method Error

Posted: 10 Oct 2016 07:38 AM PDT

I know there are question with this title, but none of them solved my problem.So, i want to do this in the application.html.erb

<% @food_types.each do |ft| %>  <%= ft.name %>  <%end%>  

And i have this in my application_controller.rb

@food_types = FoodType.all  

Here is the migration for the FoodTypes table.

class CreateFoodTypes < ActiveRecord::Migration    def change      create_table :food_types do |t|        t.string :name        t.timestamps null: false      end    end  end  

What should i do for this error ? undefined method `each' for nil:NilClass

default application controller

class ApplicationController < ActionController::Base     # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception       @food_types = FoodType.all   end  

How do I extract a field from an array of my models in order to form a single query?

Posted: 10 Oct 2016 07:36 AM PDT

I'm using Rails 4.2.7. I have an array of my model objects and currently I'm iterating through that array to find matching entries in the database based on a field my each object …

    my_object_times.each_with_index do |my_object_time, index|        found_my_object_time = MyObjectTime.find_by_my_object_id_and_overall_rank(my_object_id, my_object_time.overall_rank)  

My question is, how can I rewrite the above to run one query instead of N queries, if N is the size of the array. What I wanted was to force my underlying database (PostGres 9.5) to do a "IF VALUE IN (…)" type of query but I'm not sure how to extract all the attributes from my array and then pass them in appropriately to a query.

devise popover perform action after sign in

Posted: 10 Oct 2016 07:23 AM PDT

I have a web app where a user can favorite items. I added a popover with a bootstrap modal so when a user that is not logged in try to favorite the item the popover appears.

The popover is working but once a user sign up I'd like to have the item favorited automatically.

I tried to add an hidden field on the pop up form like this

<div class="actions">    <%= hidden_field_tag("page_id", "favorite") %>                          <%= f.submit "Log in", class: "btn btn-submit" %>  </div>  

on application_controller I have

def after_sign_in_path_for(resource)    if params[:page_id] == "favorite"      favorite_item_path(@item, type: "favorite", method: :put)    end  end  

and my items_controller I have

def favorite    @item = Item.find(params[:id])       type = params[:type]    if type == "favorite"      current_user.favorites << @item      redirect_to :back      elsif type == "unfavorite"      current_user.favorites.delete(@item)      redirect_to :back      else      redirect_to :back, notice: 'Nothing happened.'    end    end  

but when i try i get this error

No route matches {:action=>"favorite", :controller=>"items", :id=>nil, :method=>:put, :type=>"favorite"} missing required keys: [:id]

How can I make sure that the item_is loaded so that the favorite could be added automatically right after the sign up?

thanks

Rspec how to write my test?

Posted: 10 Oct 2016 07:09 AM PDT

In my app where you can create tutorials I am starting to test it and I am having hard time to create correct test.

here is what I have in spec/features/tutos/create_spec.rb

How should I write the def create_tuto ??

require "spec_helper"  require "rails_helper"    context "Creating a tuto" do    let!(:user){ User.create(first_name: "John", last_name: "Doe", email: "john@email.com", password:"password", password_confirmation:"password")  }      def create_tuto(options={})      options[:title]    ||= "My tuto"      options[:category] ||= "Ruby"      options[:content]  ||= "This contains markdown language"        visit "en/tutos"      click_link "create_tuto"      expect(page).to have_content("Create your tutorial")        fill_in "Title",  with: options[:title]      #I don't know here how to do the dropdown select ?      select("Ruby", from: "Chose a category")      fill_in "Content", with: options[:content]      click_button "Save"    end      it "redirect to the tuto list show page on success" do      create_tuto      expect(page).to have_content("Tuto was successfully created")    end    end  

When I launch the test I always have a problem with

 Capybara::ElementNotFound:         Unable to find link "create"  

My create tuto is at the bottom of my partial search form: views/tutos/_search_form.html.slim

h1.text-gray =t("search_form.title")   .search_banner    .row      .col-xs-12.col-sm-4        =form_tag tutos_path, :method => 'get' do           =text_field_tag :search, params[:search],  placeholder: t("search_form.keyword"), class: 'search-form'          =submit_tag t("search_form.search"), class:'btn btn-xs btn-default btn-search'          br          br        .col-xs-12.col-sm-4        =form_tag tutos_path, :method => 'get' do           =select_tag :select,               options_for_select(User.order('nickname ASC').all.map{|u| u.nickname}, params[:select]),               { include_blank: t("search_form.select_user"), class: 'search-form' }            =submit_tag t("search_form.select"), class:"btn btn-xs btn-default btn-search"          br          br        .col-xs-12.col-sm-4        =form_tag tutos_path, :method => 'get' do           =select_tag :filter,                 options_for_select(Category.all.map{|c| c.name}, params[:filter]),                { include_blank: t("search_form.select_cat"),  class: 'search-form' }            =submit_tag t("search_form.search"), class:"btn btn-xs btn-default btn-search"          br          br      hr      .row      .col-xs-12.col-sm-3        = link_to t("search_form.best"),  best_voted_path, class: "btn btn-default"         .col-xs-12.col-sm-3        -if user_signed_in?          = link_to t("search_form.create"), new_tuto_path, class:"btn btn-default", id:"create_tuto"  

views/tutos/_tutos_form.html.slim This the partial to create a new tutorial

= simple_form_for @tuto do |f|    - if @tuto.errors.any?      #error_explanation        h2 = "#{pluralize(@tuto.errors.count, "error")} prohibited this tuto from being saved:"        ul          - @tuto.errors.full_messages.each do |message|            li = message    = f.hidden_field :user_id, value: current_user.id    = f.input :title, label: t('tutos_form.title')    = f.collection_select :category_id, Category.all, :id, :name, { include_blank: t("tutos_form.category"), class: 'search-form' }    = f.input :content, label: t('tutos_form.content'), as: :text, input_html: { rows: "15" }    = f.button :submit, t("tutos_form.save")  

Looking forward to hearing from you ! Thanks

Export to Pdf via rails

Posted: 10 Oct 2016 07:13 AM PDT

I need to generate report to pdf file, save on the server, than send the file to the client by email.

I am looking to a gem for exporting pdf file

And I want to know if the file keep all the pdf options (like links and the option to select text copy text etc')

Thanks

Issue with an authenicated POST to Rails using curl

Posted: 10 Oct 2016 07:47 AM PDT

I'm looking to POST to a Rails app from curl. I have been able to authenticate and get a 200 response. But when I attempt to POST some data it fails.

My controller code:

class TestApiController < ApplicationController     before_action :authenticate      def server_reporter     puts params    end       protected     def authenticate       authenticate_or_request_with_http_token do |token, options|         # User.find_by(auth_token: token)          token == '1234'       end     end  end  

when I run this

curl -v localhost:3000/test_api/server_reporter -IH "Authorization: Token token=1234"

I get

Started HEAD "/test_api/server_reporter" for ::1 at 2016-10-10 11:27:19 +0200  Processing by TestApiController#server_reporter as */*  {"controller"=>"test_api", "action"=>"server_reporter"}    Rendered test_api/server_reporter.html.erb within layouts/application (0.2ms)  Completed 200 OK in 221ms (Views: 220.2ms | ActiveRecord: 0.0ms)```  

when I try

curl -v localhost:3000/test_api/server_reporter -X POST  -H "Authorization: Token token=1234"   -H "Content-Type: application/json" -d '{"server": {"name": "Asterix"}}'   

I get the following in the Rails console.

Started POST "/test_api/server_reporter" for ::1 at 2016-10-10 15:59:36 +0200  Processing by TestApiController#server_reporter as */*    Parameters: {"server"=>{"name"=>"Asterix"}, "test_api"=>{"server"=>{"name"=>"Asterix"}}}  Can't verify CSRF token authenticity  Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)    ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken:  

Edit: adding the curl response.

$ curl -v localhost:3000/test_api/server_reporter -X POST  -H "Authorization: Token token=1234"   -H "Content-Type: application/json" -d '{"server": {"name": "Asterix"}}'   *   Trying ::1...  * Connected to localhost (::1) port 3000 (#0)  > POST /test_api/server_reporter HTTP/1.1  > Host: localhost:3000  > User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)  > Accept: */*  > Referer:   > Authorization: Token token=1234  > Content-Type: application/json  > Content-Length: 31  >   * upload completely sent off: 31 out of 31 bytes  < HTTP/1.1 422 Unprocessable Entity  < Content-Type: text/plain; charset=utf-8  < X-Meta-Request-Version: 0.4.0  < X-Request-Id: a13faa8e-20b4-4107-ba5f-1c6fde1f8ce1  < X-Runtime: 0.077414  < Set-Cookie: __profilin=p%3Dt; path=/  < Connection: close  < Server: thin  <   ActionController::InvalidAuthenticityToken at /test_api/server_reporter  =======================================================================    > ActionController::InvalidAuthenticityToken  

Replacing partial with AJAX in Rails 4: undefined method `id`

Posted: 10 Oct 2016 07:08 AM PDT

When replacing a partial through Ajax, one method is giving me the proper result but the other (almost identical) isn't. I want to select and deselect a group for a specific campaign. Selecting gives me a direct replacement, deselecting doesn't.

models/general_connection.rb

belongs_to :campaign  belongs_to :group  

models/group.rb

has_many :general_connections  has_many :campaigns, through: :general_connections  

models/campaign.rb

has_many :general_connections  has_many :groups, through: :general_connections  

controllers/general_connection.rb

def connect_group_to_campaign    @group = Group.find(params[:group_id])    @campaign = Campaign.find(params[:campaign_id])    @campaign.general_connections.create(group: @group)    respond_to do |format|          format.html { redirect_to :back }          format.js    end  end    def disconnect_group_from_campaign    @general_connection = GeneralConnection.where("group_id = ? AND campaign_id = ?", params[:group_id], params[:campaign_id]).first    @group = @general_connection.group      @general_connection.destroy    respond_to do |format|          format.html { redirect_to :back }          format.js    end  end  

views/campaign/show.html.erb

<div class="row">      <% @main_groups.each do |group| %>          <%= render partial: 'groups_form', locals: { group: group } %>      <% end %>  </div>  

*views/campaign/_groups_form.html.erb

<div class="row" id="group_<%= group.id %>">      <div class="col m6">          <div class="valign-wrapper black-text">              <% if group.icon.nil? %>                  <i class="material-icons">group</i>              <% else %>                  <i class="material-icons"><%= group.icon %></i>              <% end %>                  &nbsp;&nbsp<%= group.title %>          </div>      </div>      <div class="col m6">          <% if !grouped(group) %>                              <%= form_tag connect_group_to_campaign_path(:group_id => group.id, :campaign_id => @campaign.id), remote: true do %>                  <%= button_tag 'check_box_outline_blank', class: "secondary-content material-icons grey-text", style: "background-color:white;border:none;" %>              <% end %>          <% else %>              <%= form_tag disconnect_group_from_campaign_path(:group_id => group.id, :campaign_id => @campaign.id), remote: true do %>                  <%= button_tag 'check_box', class: "secondary-content material-icons grey-text", style: "background-color:white;border:none;" %>              <% end %>          <% end %>      </div>  </div>  

views/general_connection/connect_group_to_campaign.js.erb

$('#group_<%= @group.id %>').replaceWith('<%= j render partial: 'campaigns/groups_form', locals: {group: @group} %>');  

views/general_connection/disconnect_group_from_campaign.js.erb

$('#group_<%= @group.id %>').replaceWith('<%= j render partial: 'campaigns/groups_form', locals: {group: @group} %>');  

...and this is the error that I'm getting:

ActionView::Template::Error (undefined method `id' for nil:NilClass):  12:                     </div>  13:                     <div class="col m6">  14:                         <% if !grouped(group) %>                  15:                             <%= form_tag connect_group_to_campaign_path(:group_id => group.id, :campaign_id => @campaign.id), remote: true do %>  16:                                 <%= button_tag 'check_box_outline_blank', class: "secondary-content material-icons grey-text", style: "background-color:white;border:none;" %>  17:                             <% end %>  18:                         <% else %>  

To sum it up: both methods are working, but only connect_group_to_campaign gives a direct result and disconnect_group_from_campaign doesn't and needs a browser refresh.

Can anyone help me out?

Mini_Magick and CarrierWave not resizing image

Posted: 10 Oct 2016 07:24 AM PDT

Inside my avatar_uploader.rb i have this defined

include CarrierWave::MiniMagick  process resize_to_fit: [100, 100]  

Image uploading works perfectly fine. Its the resizing that i'm having trouble with. No errors, nothing like that. The images just aren't resizing at all. I even tried hard coding the sizing into my index.html.erb view like this

<%= image_tag(tutor.profile.avatar.url, size: "50, 50") if tutor.profile.avatar? %>  

But it doesn't work as well. I have read CarrierWave and MiniMagick gem github pages and apparently there's no other additional steps.

Does anyone know if i missed anything?

rails Datatables checkbox works first page incorporating javascript solution to hide checkbox input

Posted: 10 Oct 2016 07:00 AM PDT

I have a row of checkboxes as the first row. I have a check all/deselect all checkboxes feature. Currently the check all (and individual checks) only work on the first page.

This happens because

jQuery DataTables removes non-visible rows from DOM for performance reasons, that is why when you submit the form only visible checkboxes get submitted.

and the solution is

You may need to turn those that are checked and don't exist in DOM into upon form submission.

It is this question -> Checkboxes only work on first page - Datatables, rails

I have been tinkering with this jsfiddle -> https://jsfiddle.net/gyrocode/07Lrpqm7/

I am using rails so this is my content_for

<%= content_for :footer_js do %>    $('input.date').datepicker({dateFormat: "dd-mm-yy"});      $('.filter').change(function(){      $(this).closest('form').trigger('submit');    });      var oTable1 = $('#reporttypes').dataTable({      aoColumns: [{ "bSortable": false      }, null, null, null, null, null, null, null, null, null],      aaSorting: [[10, 'desc']],      bProcessing: true,      bServerSide: true,      sAjaxSource: $('#reporttypes'),      bPaginate: true,      iDisplayLength: 25,      aLengthMenu: [25,50,100]    });      $('#example-select-all').on('click', function(){      // Get all rows with search applied      //var rows = table.rows({ 'search': 'applied' }).nodes();      // Check/uncheck checkboxes for all rows in the table      $('input[type="checkbox"]', rows).prop('checked', this.checked);    });      // Handle click on checkbox to set state of "Select all" control    $('#example tbody').on('change', 'input[type="checkbox"]', function(){      // If checkbox is not checked      if(!this.checked){          var el = $('#example-select-all').get(0);          // If "Select all" control is checked and has 'indeterminate' property          if(el && el.checked && ('indeterminate' in el)){            // Set visual state of "Select all" control            // as 'indeterminate'            el.indeterminate = true;          }      }    });       // Handle form submission event    $('#frm-example').on('submit', function(e){      var form = this;        // Iterate over all checkboxes in the table      oTable1.$('input[type="checkbox"]').each(function(){          // If checkbox doesn't exist in DOM          if(!$.contains(document, this)){            // If checkbox is checked            if(this.checked){                // Create a hidden element                $(form).append(                  $('<input>')                      .attr('type', 'hidden')                      .attr('name', this.name)                      .val(this.value)                );            }          }      });    });  <% end %>  

and here is my html

  <div class="table-responsive">      <form id="frm-example" action="/path/to/your/script" method="POST">        <table id="reporttypes" class="table table-striped table-bordered table-hover" data-source="<%= list_admin_report_types_path(format: 'json') %>">          <thead>            <tr>              <!--<th class="select-row" data-orderable="false"></th>-->              <th><input type="checkbox" name="select_all" value="1" id="example-select-all" style = "width: 20px; height: 20px"></th>              <th>Order number</th>              <th>Member Source</th>              <th>Last name</th>              <th>First name</th>              <th>Email</th>              <th>Name of DNA Report</th>              <th>Lab Result Ready</th>              <th>PDF Report Ready</th>              <th>Order Submission Date</th>            </tr>          </thead>          <tbody>          </tbody>        </table>      </form>    </div>  

I understand the js snippets but just couldn't get the last one to work. $('#frm-example') The checkbox got lost when I click next because I have pagination. Not sure if this helps anybody.

and the footerjs is yielded into this layout file

<script type="text/javascript">    $( document ).ready(function() {      jQuery(function($) {        $('table th input:checkbox').on('click' , function(){          var that = this;          $(this).closest('table').find('tr > td:first-child input:checkbox')          .each(function(){            this.checked = that.checked;            $(this).closest('tr').toggleClass('selected');          });        });          $('[data-rel="tooltip"]').tooltip({placement: tooltip_placement});        function tooltip_placement(context, source) {          var $source = $(source);          var $parent = $source.closest('table')          var off1 = $parent.offset();          var w1 = $parent.width();            var off2 = $source.offset();          var w2 = $source.width();            if( parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2) ) return 'right';          return 'left';        }          <%= yield :footer_js %>      });    });  </script>  

Mongoid changed? or changed

Posted: 10 Oct 2016 06:53 AM PDT

I'm using Rails 4 and Mongoid 4, as well as Mongoid [Enum] (https://github.com/thetron/mongoid-enum) and when I change the enum parameter and do a @model.changed? I get a false as response and if I try @order._status_changed? I also get a false. Here's my Model:

    class Order          include Mongoid::Document        include Mongoid::Timestamps        include Mongoid::Enum        include Mongoid::Slug        include Mongoid::Paperclip          enum :status, [:new_order, :processing, :completed, :cancelled, :updated, :partially_refunded,                       :completed_add_on, :ready_to_download, :incomplete, :podcast_production,                       :pam_production, :unpaid], :default => :unpaid           ...        end  

So I'm definitely changing the status property of the model but why it doesn't seem to be captured in @order.changed?

Any ideas?

Photoswipe with Justified Gallery

Posted: 10 Oct 2016 06:44 AM PDT

I successfully set up Photoswipe and also Justified Gallery in my Rails project. Both of them work very nicely alone but I have trouble making them work together.

In my current (default) setup Photoswipe expects a tag hierarchy as follows:

<figure>    <a href="...>      <img src=".../>    </a>  

Justified Gallery is configured by default to recognize a container with any number of <a> tags with a nested <img> tag within like this:

<div id="mygallery" >      <a href="...>          <img src=".../>      </a>      <a href="...>          <img src=".../>      </a>      <!-- other images... -->  </div>  

So I would need to have Justified Gallery recognizing that <figure> tag. In their documentation it says you just have to add the following option:

selector: 'figure, div:not(.spinner)'  

This part seems to work fine but it is also mentioned that it is necessary to extend the CSS rules and this is where I'm stuck. I would expect that prepending all or some > a selectors with a > figure selector should do the job but no. These are the rules that come with Justified Gallery:

.justified-gallery {    width: 100%;    position: relative;    overflow: hidden;  }  .justified-gallery > a,  .justified-gallery > div {    position: absolute;    display: inline-block;    overflow: hidden;    opacity: 0;    filter: alpha(opacity=0);    /* IE8 or Earlier */  }  .justified-gallery > a > img,  .justified-gallery > div > img,  .justified-gallery > a > a > img,  .justified-gallery > div > a > img {    position: absolute;    top: 50%;    left: 50%;    margin: 0;    padding: 0;    border: none;  }  .justified-gallery > a > .caption,  .justified-gallery > div > .caption {    display: none;    position: absolute;    bottom: 0;    padding: 5px;    background-color: #000000;    left: 0;    right: 0;    margin: 0;    color: white;    font-size: 12px;    font-weight: 300;    font-family: sans-serif;  }  .justified-gallery > a > .caption.caption-visible,  .justified-gallery > div > .caption.caption-visible {    display: initial;    opacity: 0.7;    filter: "alpha(opacity=70)";    /* IE8 or Earlier */    -webkit-animation: justified-gallery-show-caption-animation 500ms 0 ease;    -moz-animation: justified-gallery-show-caption-animation 500ms 0 ease;    -ms-animation: justified-gallery-show-caption-animation 500ms 0 ease;  }  .justified-gallery > .entry-visible {    opacity: 1.0;    filter: alpha(opacity=100);    /* IE8 or Earlier */    -webkit-animation: justified-gallery-show-entry-animation 500ms 0 ease;    -moz-animation: justified-gallery-show-entry-animation 500ms 0 ease;    -ms-animation: justified-gallery-show-entry-animation 500ms 0 ease;  }  .justified-gallery > .jg-filtered {    display: none;  }  .justified-gallery > .spinner {    position: absolute;    bottom: 0;    margin-left: -24px;    padding: 10px 0 10px 0;    left: 50%;    opacity: initial;    filter: initial;    overflow: initial;  }  .justified-gallery > .spinner > span {    display: inline-block;    opacity: 0;    filter: alpha(opacity=0);    /* IE8 or Earlier */    width: 8px;    height: 8px;    margin: 0 4px 0 4px;    background-color: #000;    border-top-left-radius: 6px;    border-top-right-radius: 6px;    border-bottom-right-radius: 6px;    border-bottom-left-radius: 6px;  }  

I have been playing around with this for quite a while but I can't make this work. Also I haven't been able to find a good example on the net.

Anyone has done this before or knows how to solve it?

Filtered Search in Rails 4 using ActiveRecord Querying Interface

Posted: 10 Oct 2016 06:49 AM PDT

I have some filters in place when performing a search. I have another search filter that I am trying to implement, but can't seem to get it to work. I am having issues with the first_name last_name and building the view for that.

Controller:

if params[:address_search]     @payment_requests = @payment_requests.where('full_address ILIKE ?', "%#{params[:address_search]}%")       unless params[:unit_search].blank?        @payment_requests = @payment_requests.where('unit ILIKE ?', "%#{params[:unit_search]}%")     end  elsif params[:client_search]     @payment_requests = @payment_requests.where('email ILIKE ?', "%#{params[:client_search]}%")  elsif params[:first_name] || params[:last_name]     @payment_requests = PaymentRequest.includes(:detail).where(payment_details: { first_name: params[:first_name], last_name: params[:last_name]})     end  else     @payment_requests = @payment_requests.active  end  

Views:

<div class="form-group">     <%= text_field_tag 'client_search', '', id: 'pay-client-search', placeholder: 'Email Search', class: 'general-text-area pay-filter' %>  </div>  

Dynamic Paperclip Watermark path

Posted: 10 Oct 2016 06:31 AM PDT

I'm looking for generating custom watermark for a Paperclip class depending on a current_user's attribute value to generate the path. What is the best practice in order to achieve that? Here is what I've tried until now

Current:

class Current    cattr_accessor :logo  end  

ApplicationController:

class ApplicationController < ActionController::Base    before_action :set_logo      private    def set_logo      Current.logo = user_signed_in? ? current_user.cold_storage + ".png" : DEFAULT_LOGO    end  end  

And then call it within Asset

class Asset < ActiveRecord::Base      has_attached_file :file,            url: ":s3_domain_url",            processors: [:watermark],            styles: {              medium: {                geometry: "400x400>",                watermark_path: "#{Rails.root}/public/images/watermarks/#{Current.logo}"              },            },            path: "/:class/:attachment/:id_partition/:style/:filename"  end  

Uninitialized constant Sidekiq::ConnectionPool with sidekiq 4.1.4 on ubuntu

Posted: 10 Oct 2016 06:18 AM PDT

Im trying to run bundle exec sidekiq on ubuntu 16 after installation of Sidekiq but got this error. Could someone please help?

redirect_to @article doesn't work. article_url not defined

Posted: 10 Oct 2016 06:20 AM PDT

As I said above. I use my code like this.

class ArticlesController < ApplicationController    def show      @article = Article.find(params[:id])    end    def new    end    def create      @article = Article.new(article_params)      @article.save      redirect_to @article    end      private      def article_params        params.require(:article).permit(:title, :text)      end  end  

But it always doesn't work. I have no idea and other questions are no use. This is my template.

<%= form_for :article,url: articles_path do |f| %>    <p>      <%= f.label :title %><br>      <%= f.text_field :title %>    </p>      <p>      <%= f.label :text %><br>      <%= f.text_area :text %>    </p>      <p>      <%= f.submit %>    </p>  <% end %>  

Jquery autonumeric (gem 'autonumeric-rails') not loading correctly

Posted: 10 Oct 2016 07:50 AM PDT

Jquery autonumeric is not loading correctly on page load. If I refresh the page the jquery works, but provides 0.00, not the specified, 0 as specified here: $('input.number').number( true, 0 );

Two issues I need to solve:

1) why it is not loading on the original page load

2) why $('input.number').number( true, 0 ); is not working in setting the parameters.

GemFile

gem 'autonumeric-rails'  

application.js

//= require jquery  //= require jquery_ujs  //= require autonumeric  //= require bootstrap-sprockets  //= require turbolinks  //= require dynamic_select    $('input.number').number( true, 0 );  

I also tried this:

application.js (second version)

//= require jquery  //= require jquery_ujs  //= require autonumeric  //= require bootstrap-sprockets  //= require turbolinks  //= require dynamic_select    $(document).ready(function() {               $('input.number').number( true, 0 );              $(document).trigger('refresh_autonumeric');      });  

_form.html.erb

<%= f.text_field( :income,{value: 50000, :placeholder => "Income", class: "number form-control input-lg", data: {autonumeric: true} } ) %>  

update:

Removing $('input.number').number( true, 0 ); seemed to get the below working. However #2 is still an issue. I can't get .number(true, 0) working

$(document).ready(function() {         $(document).trigger('refresh_autonumeric');  });  

How to use ajax in Rails for destroy method?

Posted: 10 Oct 2016 06:40 AM PDT

I want to make an option "delete" for my items based on ajax.

items_controller:

def destroy    @item.destroy    respond_to do |format|      format.js { render :layout => false }    end  end  

destroy.js.erb:

$('div#item_<%= item.id %>').bind('ajax:success', function() {     $(this).fadeOut();  });  

_item.html.erb:

<div class='item' id="item_<%= item.id %>">    <span class="item_image"><%= image_tag item.image.url(:thumb) %></span>    <span class="price"><%= item.price %></span>    <span class="item_name"> <br>       <%= item.name %>    </span> <br>     <span class="small-text text-center">    <% str = item.short_description %>    <%= str[0..70] + "..." if str %>    </span>    <br>    <div class="small-2 large-4 columns rating_stars">      <% if true %>        <%= rating_for item, "rating", half_show: true, cancel_place: :right  %>      <% end %>    </div>    <div class='to_cart'>      <%= link_to 'В корзину', to_cart_item_path(item), method: :put, class: 'a_to_cart' %>      </div>      <span class='delete_my'>      <%= link_to 'delete', item, method: :delete, remote: true %>    </span>  </div>  

Tell me please, what I do wrong? I'm very bad in ajax and js.

How to group the records based to 3rd table belongs to, has many

Posted: 10 Oct 2016 06:24 AM PDT

I have below code:

quiz.rb

has_many :quiz_attempts  

student.rb

has_many :quiz_attempts  

quiz_attempt.rb

belongs_to :student  belongs_to :quiz  

What I need to do is to get all records of student from quiz_attempts table which has quiz id and show the records of quiz table based on it.

Means, if students has taken one quiz A 10 times and quiz B 5 times, so I need to show all these rows as 2 from quiz table.

In view I will have only 2 records of quiz table which are associated with 15 records of A and B collectively in quiz_attempts table.

quiz_attempts has quiz_id column and student_id column as well, quiz table has no student id in it.

The query I am working with is:

@quizzes   = @student.quiz_attempts.includes(:quiz)  

but the problem is that, it still shows me 2 rows but from quiz_attempts table and I cant group them as quiz table.

I need to have complete solution.

Dividing a time period into multiple periods

Posted: 10 Oct 2016 05:56 AM PDT

Let's say I have a time period in two variables (from start_date to end_date). Is there an easy way to split it into a smaller periods? Important thing is, I want results to be rounded up. If it's not clear what I mean, here's an example:

I have period from 15.01.2016 to 10.06.2016. I want to split in into months, so I will have six periods. 01.01.2016 - 31.01.2016
01.02.2016 - 31.02.2016
01.03.2016 - 31.03.2016
01.04.2016 - 31.04.2016
01.05.2016 - 31.05.2016
01.06.2016 - 31.06.2016

I want to include the time between 01.01.2016 and 15.01.2016 regardless of the fact, that it is not in the original period.

I've been looking for some ideas, but at this time it seems, that the only way is using the start date, and iterating (using DateAndTime::Calculations to determine the borders of intervals), until hitting the end date.

Rails, mounting engines at different points in the routes file.

Posted: 10 Oct 2016 05:25 AM PDT

I would like to understand why the following examples do not produce routes as I would have expected them to and how, if at all, I can implement routes from mounted engines in this fashion.

  namespace :admin do       mount MyEngine::Engine => "/"    end      # I realise I could just as easily do this     # mount MyEngine::Engine => "/admin"    # but it would help answer the example example below       resources :events do      member do         mount MyEngine::Engine => "/"      end    end  

Currently the engine's routes are generated outside of the 'events' or 'admin' blocks. Meaning regardless of where I put them, the engine's routes always appear at the root level.

I've had a look through devise's source code and understand they do something funky with the 'devise_for' method, enabling more customisable routes. Hints, links to decent tutorials, or help on how to implement this within my own application would be greatly received.

Thanks in advance.

Entered Details Incorrectly when installing rails

Posted: 10 Oct 2016 05:38 AM PDT

I entered my details incorrectly when installing rails 'www.railsinstaller.org'.

It asked me to enter my details on CMD I.E Name, Github account details. I entered them incorrectly and when I try to re-do the install, it does not give me the option to re-enter them, and I need to! Here is my screen:

image

The details must of been saved to a secret file somewhere that isn't deleted when I uninstall and re-install.

What should I do? Help would be grand!

Benjamin

Rails Model Associations when nesting - Confusion

Posted: 10 Oct 2016 07:13 AM PDT

Perhaps I am approaching this all wrong, I have the following models setup:

The User model has many Questions, a Question belongs_to a User

This means I can easily do: u = User.last.questions and see all of the questions associated with the user last added.

Following this, I have a Payment model that belongs_to a Question. A Question has_one payment meaning I can easily do u = User.last.questions.last.payment, getting the payment details from the question last added by the last added user (daft example perhaps!).

Now the bit that is confusing me

I have a model called PaymentOption which is used to populate a drop down list, for different prices, the PaymentOption belongs_to a Payment and a Payment has_one PaymentOption

This is all working correctly, but the only way for me to find out the details of the payment option, such as the amount, would be to do something like this:

payment_amount = PaymentOption.find(User.last.questions.last.payment.payment_option_id).amount

Ideally I would do something like this: amount = User.last.questions.last.payment.payment_option.amount

By doing it in the way I have, it is as good as doing two seperate queries, one to get the payment option ID and another to find a detail relating to that particular payment option. Surely there is a better way to approach this?

Thanks in advance

EDIT 1

To clarify my answer, I have included the schema for Payments and PaymentOptions

create_table "payment_options", force: :cascade do |t|    t.integer  "amount"    t.text     "description"    t.string   "title"    t.boolean  "user_accessible", default: true    t.datetime "created_at",                     null: false    t.datetime "updated_at",                     null: false  end    create_table "payments", force: :cascade do |t|    t.string   "email"    t.string   "token"    t.integer  "question_id"    t.datetime "created_at",        null: false    t.datetime "updated_at",        null: false    t.integer  "payment_option_id"  end    add_index "payments", ["payment_option_id"], name:    "index_payments_on_payment_option_id"  add_index "payments", ["question_id"], name: "index_payments_on_question_id"  

Stripe javascript not retrieving the token I need to create a charge

Posted: 10 Oct 2016 05:16 AM PDT

I am trying to process a payment using a simple stripe charge, the user must pay a quantity in the website through a form and, basically, I don´t know why i am not getting the token back, I think my javascript is not being executed actually. Here is the code:

This is the form placed in order#new (the form view)        :javascript      Stripe.setPublishableKey("<%= ENV['STRIPE_TEST_PUBLISHABLE_KEY] %>");    .container.body-content      %h2           Complete order:           = @cart.name      %table.table.table-items          %tr              %th Design name              %th Quantity              %th Price          - @cart.cart_items.each do |c|              %tr                  %td= c.design.name                  %td= c.quantity                  %td= c.design.price          %tr              %th Total price              %th              %th= @total_price      = simple_form_for(@order, html: { role: "form", class: "cc_form" }) do |f|          = f.simple_fields_for( :payment ) do |p|              .row.col-md-12                  .form-group.col-md-4.no-left-padding                      = p.input :card_number,                           label: "Card Number",                           label_html: { data: { stripe: "label" } },                          input_html: { required: "true", data: { stripe: "number" }, class: "form-control" }                  .form-group.col-md-2                      = p.input :card_cvv,                           label: "Card CVV",                           label_html: { data: { stripe: 'label' } },                          input_html: { required: "true", data: { stripe: "cvv" }, class: "form-control" }                  .form-group.col-md-6                      .col-md-12                          = p.label :card_expires, "Card expires", data: { stripe: 'label' }                      .col-md-3                          = p.select :card_expires_month, options_for_select(Payment.month_options), { include_blank: 'Month' }, data: { stripe: "exp-month" }, class: "form-control", required: true                      .col-md-3                          = p.select :card_expires_year, options_for_select(Payment.year_options.push), { include_blank: 'Year' }, data: { stripe: "exp-year" }, class: "form-control", required: true          = f.hidden_field :cart_id, :value => @cart.id          = f.hidden_field_tag 'cart', @cart.id          = f.hidden_field_tag 'total_price', @total_price          = f.button :submit, "Pay and finish order", class: "btn btn-login"  

This is orders_controller.rb:

class OrdersController < ApplicationController        include ApplicationHelper        def index      end        def new          @order = current_user.orders.build          @cart = Cart.find(params[:format])          @payment = @order.build_payment          @total_price = get_total_price_for_navigation_bar      end        def create          @order = current_user.orders.build(order_params)          @cart = Cart.find(params[:cart])          @payment = @order.build_payment          @payment.user_id = current_user.id          process_payment(params[:total_price])          if payment.save              if @order.save                  @cart.purchased = true                  @cart.total_price = params[:total_price]                  @cart.save                  flash[:success] = "Order created"                  redirect_to orders_path              else                  flash[:danger] = "Order couldn´t be saved, please try again"                  render :new              end          else              flash[:danger] = "There was a problem processing your payment, please try again"              render :new          end      end        private          def order_params              params.require(:order).permit(:cart_id)          end            def process_payment(amount)              #byebug              token = params[:stripeToken]              byebug              # Create a charge: this will charge the user's card              begin                charge = Stripe::Charge.create( :amount => amount * 100, :currency => "eur", :source => token, :description => "Example charge")              rescue Stripe::CardError => e                # The card has been declined              end          end  end  

and to process the payment I have created credit_card_form.js (of course under assets -> javascripts (I have also removed the turbolinks from application.js )

$(document).ready(function(){      var show_error, stripeResponseHandler, submitHandler;        submitHandler = function(event){          var $form = $(event.target);          $form.find("input[type=submit]").prop("disabled", true);            //If stripe was correctly initialized this will create a token using the credit card info          if(Stripe){              Stripe.card.createToken($form, stripeResponseHandler);          } else {              show_error("Failed to load credit card processing functionality. Please reload this page in your browser.")          }          return false;      };        $(".cc_form").on('submit', submitHandler);        stripeResponseHandler = function(status, response){          var token, $form;            $form = $('.cc_form');            if (response.error) {              console.log(response.error.message);              show_error(response.error.message);              $form.find("input[type=submit]").prop("disabled", false);          } else {              token = response.id;              $form.append($('<input type="hidden" name="stripeToken">').val(token));              $form.get(0).submit();          }          return false;      };        show_error = function(message){          if($("#flash-messages").size() < 1){              $('div.container.main div:first').prepend("<div id='flash-messages'></div>")          }          $("#flash-messages").html('<div class="alert alert-warning"><a class="close" data-dismiss="alert">x</a><div id="flash_alert">' + message + '</div></div>');          $('.alert').delay(5000).fadeOut(3000);          return false;      };  });  

When I try to process a payment I never receive the token in the order#create method, so I think that the javascript is not executing

When I inspect variables in terminal I see that the token is not added to the form as a param, as I am suppose to append in stripeResponseHandler in credit_card_form.js this is the output I see when I inspect variables:

(byebug) token  nil  (byebug) params  {"utf8"=>"✓", "authenticity_token"=>"ps963bnlJwbayybIgXVAu8xQI3L6BneUK6qg5k9U9BV7XL+3M+Bl+OVJqJGNrcMHLAjhjvxOkOlhyig9Sh5Cdw==", "order"=>{"payment_attributes"=>{"card_number"=>"4012888888881881", "card_cvv"=>"123", "card_expires_month"=>"3", "card_expires_year"=>"2017"}, "cart_id"=>"9"}, "cart"=>"9", "total_price"=>"390.0", "controller"=>"orders", "action"=>"create"}  (byebug)  

Well, I don´t know if I am not seing something stupid or I am completely wrong in my approach, any suggestion will be appreciated.

Thanks in advance

Antonio

Dynamic watermark path Paperclip + Rails [Ruby]

Posted: 10 Oct 2016 05:58 AM PDT

I'm trying to set one class variable to store a name of a watermark file to be used by Paperclip on a class named Asset. The main problem that i'm stuck to is that this watermark changes depending on a devise current_user's specific attribute value. Therefore I'm unable to just set a constant in Asset model.

Current class:

class Current    cattr_accessor :logo  end  

AplicationController:

  class ApplicationController < ActionController::Base      before_action :set_logo        private      def set_logo        Current.logo = user_signed_in? ? current_user.cold_storage + ".png" : DEFAULT_LOGO      end    end  

Asset model:

    class Asset < ActiveRecord::Base        has_attached_file :file,            url: ":s3_domain_url",            processors: [:watermark],            styles: {              medium: {                geometry: "400x400>",                watermark_path: "#{Rails.root}/public/images/watermarks/#{Current.logo}"            },            path: "/:class/:attachment/:id_partition/:style/:filename"       end  

Apatana 3 debugger failing

Posted: 10 Oct 2016 04:42 AM PDT

I used Aptana's debugger in on some rails apps earlier this spring and I know it has worked for me before, but I can't get it to run on anything now.

I don't recall needing to do much configuration to get it going, and I'm not aware of any configuration changes I've made in the meantime.

For a simple test I created a new rails app ("testapp") and without playing with any of the debug configurations, I tried running the debugger on app/controllers/application_controller.rb. I get this error in the debug perspective in aptana:

Fast Debugger (ruby-debug-ide 0.6.0, debase 0.2.1, file filtering is supported) listens on 127.0.0.1:63359  Uncaught exception: uninitialized constant ActionController      /sites/veggies/testapp/app/controllers/application_controller.rb:1:in `<top (required)>'      /Users/mmutrux/.rvm/gems/ruby-2.2.5/bin/rdebug-ide:23:in `load'      /Users/mmutrux/.rvm/gems/ruby-2.2.5/bin/rdebug-ide:23:in `<main>'  /sites/veggies/testapp/app/controllers/application_controller.rb:1:in `<top (required)>': uninitialized constant ActionController (NameError)      from /Users/mmutrux/.rvm/gems/ruby-2.2.5/gems/ruby-debug-ide-0.6.0/lib/ruby-debug-ide.rb:88:in `debug_load'      from /Users/mmutrux/.rvm/gems/ruby-2.2.5/gems/ruby-debug-ide-0.6.0/lib/ruby-debug-ide.rb:88:in `debug_program'      from /Users/mmutrux/.rvm/gems/ruby-2.2.5/gems/ruby-debug-ide-0.6.0/bin/rdebug-ide:130:in `<top (required)>'      from /Users/mmutrux/.rvm/gems/ruby-2.2.5/bin/rdebug-ide:23:in `load'      from /Users/mmutrux/.rvm/gems/ruby-2.2.5/bin/rdebug-ide:23:in `<main>'  

Then if I leave things alone for a few moments I get this error dialog:

enter image description here

I installed the ruby-debug-ide gem when I first started seeing this problem (which was somewhat weird because the debugger had - apparently - been running without it previously):

/sites/veggies/testapp $ gem list | grep "debug"  debug_inspector (0.0.2)  ruby-debug-ide (0.6.0)  

It appears to be on my $PATH:

/sites/veggies/testapp $ echo $PATH  /Users/myusername/.rvm/gems/ruby-2.2.5/bin:/Users/myusername/.rvm/gems/ruby-2.2.5@global/bin:/Users/myusername/.rvm/rubies/ruby-2.2.5/bin:/opt/local/lib/php/pear/bin:[etc]  

That appears to contain my working gem environment:

/sites/veggies/testapp $ gem environment  RubyGems Environment:    - RUBYGEMS VERSION: 2.4.8    - RUBY VERSION: 2.2.5 (2016-04-26 patchlevel 319) [x86_64-darwin13]    - INSTALLATION DIRECTORY: /Users/myusername/.rvm/gems/ruby-2.2.5    - RUBY EXECUTABLE: /Users/myusername/.rvm/rubies/ruby-2.2.5/bin/ruby    - EXECUTABLE DIRECTORY: /Users/myusername/.rvm/gems/ruby-2.2.5/bin    - SPEC CACHE DIRECTORY: /Users/myusername/.gem/specs    - SYSTEM CONFIGURATION DIRECTORY: /Users/myusername/.rvm/rubies/ruby-2.2.5/etc    - RUBYGEMS PLATFORMS:      - ruby      - x86_64-darwin-13    - GEM PATHS:       - /Users/myusername/.rvm/gems/ruby-2.2.5       - /Users/myusername/.rvm/gems/ruby-2.2.5@global  

And I see the debug gem there:

/sites/veggies/testapp $ ls /Users/mmutrux/.rvm/gems/ruby-2.2.5/gems/ruby-debug-ide-0.6.0  CHANGES                ChangeLog.md           MIT-LICENSE            bin                    lib  ChangeLog.archive      Gemfile                Rakefile               ext                    ruby-debug-ide.gemspec  

So the problem must be something else. Any idea what?

How is Rails.cache variable available across threads?

Posted: 10 Oct 2016 04:25 AM PDT

If i write a value into say Rails.cache.write('foo', :bar) inside a rails controller action, how is this available inside a rails console context run at the same time?

How to properly initialise the canvas theme with turbolinks 5 in rails?

Posted: 10 Oct 2016 04:06 AM PDT

Background

I'm trying to use the canvas theme in a rails application using turbolinks 5.

The theme includes several script tags at the bottom of the html body. This way, some initialisation scripts are run after the body has been loaded.

In turbolinks, clicks to links are intercepted and the new content is loaded and inserted into the body via javascript.

Problem

Thus, to bring both, the theme and turbolinks, together, I suppose that I need to run some initialization functions of the theme in a turbolinks event like turbolinks:load.

Does anyone know which functions to call from the turbolinks events?

What I've already tried

I've tried to call the functions that are called at the bottom of the theme's js/functions.js:

# app/assets/javascripts/turbolinks_with_canvas.js.coffee  $(document).on 'turbolinks:load', ->    SEMICOLON.documentOnReady.init()    SEMICOLON.documentOnLoad.init()  

But unfortunately, this does not suffice:

  • After loading a page via turbolinks, I see just the loading spinner.
  • If I try to suppress the page transitions by adding the no-transition class to the body tag, after loading a page via turbolinks, I see the loading spinner anyway.
  • If I execute $('.css3-spinner').remove() from the browser's console, the page behind the spinner appears to have been loaded and initialised correctly.

ConnectionPool ActiveRecord questions

Posted: 10 Oct 2016 05:26 AM PDT

I'm building an advanced RoR application with several instances of database connections running concurrently. However I'm still looking for answers for the following,

  1. Does the connection handler automatically add a connection into the pool once its established? Like the following way,

    ActiveRecord::Base.establish_connection(spec)  
  2. When would it disconnect the active connection if there's no activity for a while? Or should it be manually disconnected.

  3. Are there any other alternatives to disconnecting the database connection like the following,

    ActiveRecord::Base.remove_connection(connection_object)  
  4. How can I increase the pool size which could be for different database adapters.

Looking forward to some tips.

1 comment:

  1. It is nice blog Thank you provide important information and I am searching for the same information to save my time Ruby on Rails Online Training

    ReplyDelete