jeudi 31 janvier 2019

Rails: create and destroy belongs_to association through link_to actions

I am working on an admin interface where I have images and heroes. The hero table consists in only two columns: id and image_id. I would like to be able to add and remove images to the hero table.

I have a select_to_hero and select_from hero action and view which display either all images not already connected or all existing heroes and both work, but the add_to_hero and remove_from_hero actions, which I use to create a new or destroy an existing association do not work.

Hero.rb Model

class Hero < ActiveRecord::Base
  attr_accessible :image_id
  belongs_to :image
end

Image.rb Model

class Image < ActiveRecord::Base
  attr_accessible :alt, :author, :copyright, :file_name, :title
  has_one :hero
  mount_uploader :file_name, ImageUploader
end

Select_from_hero.html.erb

<% @heroes.each do |hero| %>
  <%= link_to(image_tag(hero.image.file_name.url(:thumb), {:action => 'remove_from_hero', :id => hero}) %>
<% end %>

Select_to_hero.html.erb

<% @images.each do |image| %>
  <%= link_to(image_tag(image.file_name.url(:thumb), {:action => 'add_to_hero', :id => image}) %>
<% end %>

images_controller.rb

def add_to_hero
  @hero.image << Image.find(params[:id]) unless @hero.image.include?(Image.find(params[:id]))
  if @hero.save
    ..
  else
    render :action => 'select_to_hero'
  end
end

def remove_from_hero
  @hero.image.delete(Image.find(params[:id]))
  if @hero.save
    ..
  else
    render :action => 'select_from_hero'
  end
end

With this setting I get:

NoMethodError in Admin::ImagesController#add_to_hero
undefined method `image' for nil:NilClass

and

NoMethodError in Admin::ImagesController#remove_from_hero
undefined method `image' for nil:NilClass

But I can query an existing association:

> Hero.find(2).image
  Hero Load (0.3ms)  SELECT `heroes`.* FROM `heroes` WHERE `heroes`.`id` = ? LIMIT 1  [["id", 2]]
  Image Load (0.3ms)  SELECT `images`.* FROM `images` WHERE `images`.`id` = 1 LIMIT 1
 => #<Image id: 1, file_name: "red.jpg", title: "blu", alt: "yellow", author: "John", copyright: "Jane", created_at: "2019-01-29 19:50:25", updated_at: "2019-01-29 19:50:25"> 

How can I get this working?

mercredi 30 janvier 2019

Dragonfly - Image Width, Height Validation

In an old Rails application with Dragonfly for image uploads. In short, I would like to validate the width and height of the image to be greater than 1024 x 1024.

Looking in to the documentation I see there are 2 types of operations in: and as:.

I would like to implement validations for

  • width > 1024
  • Height > 1024

What I have so far is as...

# config/initializers/dragonfly.rb
require 'dragonfly'

app = Dragonfly[:images]
app.configure_with(:imagemagick)
app.configure_with(:rails)

app.define_macro(ActiveRecord::Base, :image_accessor)

and the modal

class Tenant < ActiveRecord::Base
  image_accessor :splash_image

  validates_size_of :splash_image, maximum: 10.megabyte, message: 'is too large (10 MB maximum)'
  validates_property :width, of: :splash_image, in: (1024...Float::Infinity), message: "image should be at least 1024px wide"
end

Thank you upfront.

js.erb file not getting triggered

I have three files: Controller:

   def index
    @filterrific = initialize_filterrific(
      DimDictionary,
      params[:filterrific],
      select_options: {},
      persistence_id: 'shared_key',
      default_filter_params: {},
      available_filters: [ :dictionary_word_filter ]
    ) || return

    @dictionaries = @filterrific.find.limit(30)

    respond_to do |format|
      format.html {render layout: false}
      format.js {render layout: false}
    end
  end

Index.html.haml

= form_for_filterrific @filterrific do |f|
  .ui.form
    .fields
      .field
        Filter Word
        = f.text_field :dictionary_word_filter
  = render_filterrific_spinner
= render(partial: '/test/list', locals: { dictionaries: @dictionaries })

Index.js.erb

<% alert("hi"); %>
<% console.log('working Mannnnn') %>
<%  js = escape_javascript(render(partial: '/test/list', locals: { dictionaries: @dictionaries })) %>
$("#filterrific_results").html("<%= js %>");

The Index.js.erb is not getting triggered. Every time the page loads, its should run the Index.js.erb and show the alert and the console.log and the show the html right?

I am here using filterrific gem for filtration purpose but the index.js.erb file never gets triggered.

Even i have includes the js format in my controller. How should it be ? am i doing something wrong?

mardi 29 janvier 2019

How to move all values above or below an insertion up one or down one in a hash

This is for a drag and drop, I have the front end working correctly and it sends data correctly to my rails backend.

I am attempting to sort a hash based on the index position that is incoming as well as only sort the Tasks that are part of the selected column @tasks = Task.where(column_id: params[:column_id]), If an index moves up the list, only update the values that are greater, and if the index moves down the list, only the values that are smaller need to be updated.

I have put comments in the code to explain what it is I believe I am doing.

I have tried many different variations of this loop, with this leading to the closest result but not quite right.

def update
  @tasks = Task.where(column_id: params[:column_id]) #get all tasks with 
column_id
  @task = Task.find(params[:id])
  if(@task[:index] < params[:index]) #current index less than incoming index
   @tasks.each do |t, v|
     next if t[:id].to_i == params[:id].to_i #skip each if t = current task
      if t[:index].to_i <= params[:index].to_i && t[:index].to_i > @task[:index].to_i 
      #if current task index is less than incoming index and current task index is less than @task index
        t.update_attribute(:index, t[:index].to_i - 1) #update task index to old index - 1
      end
    end
  else
  @tasks.each do |t, v|
    next if t[:id].to_i == params[:id].to_i //skip each if t = current task
      if t[:index].to_i >= params[:index].to_i && t[:index].to_i < @task[:index].to_i
      #if current task index is greater than incoming index and current task index is less than @task index
        t.update_attribute(:index, t[:index].to_i + 1) #update task index to old index + 1
      end
    end
  end
  @task.update_attribute(:index, params[:index].to_i)
  if @task.update(task_params)
    render json: Task.where(tasklist_id: params[:tasklist_id])
  else
    render json: @task.errors, status: :unprocessable_entity
  end
end

I excpect the index of the task to change from 1 to 5, and every value underneath to move down one, or change 5 to 1 and every value above move up one

Ruby Project Run time Error- require': cannot load such file -- bundler (LoadError)

I tried running a gitproject , https://github.com/jmopr/job-hunter in RubyMine IDE. And while running the project from menu in RubyMine IDE, the error produced is this.

--------------------------(START)-Output for run of project------------

/usr/bin/ruby /Applications/software/projects/gitprojects/job-hunter_rb/bin/rails server -b 0.0.0.0 -p 3000 -e development /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in require': cannot load such file -- bundler (LoadError) from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:inrequire' from /Applications/software/projects/gitprojects/job-hunter_rb/bin/spring:8:in <top (required)>' from /Applications/software/projects/gitprojects/job-hunter_rb/bin/rails:3:inload' from /Applications/software/projects/gitprojects/job-hunter_rb/bin/rails:3:in `'

Process finished with exit code 1

--------------------------(END)-Output for run of project------------

  • Specs:

Ruby Version (ruby 2.6.0p0 (2018-12-25 revision 66547) [x86_64-darwin16] )

rails -v Could not find proper version of railties (4.2.5.1) in any of the sources Run bundle install to install missing gems.

lundi 28 janvier 2019

Filterrific not filtering data

I am trying to use Filterrific gem to filter data. but seems like every time I type in the text field, it just refreshes page and filter. I don't want it to refresh the page and it should be instant.

Controller:

  def index
    dictionary_types = DimDictionary::DISPLAY_TYPE.map{|key, value| value }
    @dictionary_types_array = DimDictionaryType.where(dictionary_type_name: dictionary_types).pluck(:dictionary_type_name, :dictionary_type_id)
    @filterrific = initialize_filterrific(
      fetch_dictionary_collection,
      params[:filterrific],
      select_options: {},
      persistence_id: 'shared_key',
      default_filter_params: {},
      available_filters: [
          :dictionary_word_filter
        ],
    ) || return

    @dictionaries = @filterrific.find

    respond_to do |format|
      format.html
      format.js
    end
  end

Created three files:

Index.html.haml

= form_for_filterrific @filterrific do |f|
  .ui.form
    .fields
      .field
        Filter Word
        = f.text_field :dictionary_word_filter

  = render_filterrific_spinner

= render(partial: 'test/list', locals: { dictionaries: @dictionaries, dictionary_types_array: @dictionary_types_array })

Index.js.erb

<%  js = escape_javascript(render(partial: 'test/list', locals: { dictionaries: @dictionaries, dictionary_types_array: @dictionary_types_array })) %>

$("#filterrific_results").html("<%= js %>");

_list.html.haml

#filterrific_results
  %strong Test Is Working
  %table.table.dictionary-table
    %thead
      %tr
        %th #
        %th Type
        %th Word
        %th Replacement
    %tbody#dictionary-content-area.clusterize-content
      - counter = 0
      - dictionaries.each do |dictionary|
        - counter = counter + 1
        %tr{ data: {id: dictionary.dictionary_id, index: counter, type: dictionary.dim_dictionary_type.dictionary_type_id}}
          %td
            = counter
          %td#dictionary-type
            = dictionary.dim_dictionary_type.dictionary_type_name
          %td#original-word
            = dictionary.dictionary_word
          %td#replaced-word
            = dictionary.dictionary_replacement

Am I doing something wrong here? This is all I have added.

Saving date field as dd/mm/yyyy rails

We have a date_of_birth field of date type in our User model.

When I am trying to save my User object.

u = User.last
u.date_of_birth = "31-03-1987"
u.save

results:

u.date_of_birth
=> Tue, 31 Mar 1987

but If I replace - with /

u.date_of_birth = "31/03/1987"
u.save

results:

u.date_of_birth
=> nil

Question

Is this is a default behaviour?

Rails 3

Postgres

unexpected token at '(node:7103) DeprecationWarning: 'root' is deprecated, use 'global' '

I am working on a ruby on rails project and when I have add some coffee-script in haml view file then it gives error. I am wondering from last day why this happening

784: unexpected token at '(node:7486) [DEP0016] DeprecationWarning: 'root' is deprecated, use 'global'

coffee-script code

:coffeescript
  $ ->
    $('#chaperone').click (event) ->
      console.log('testing')

If i have remove this code from haml view file then it works fine but what is wrong with this code?? how can i fix it??

dimanche 27 janvier 2019

why after_add in rails 5 is executing method without an object is being created

I am not able to understand why after_add is executing method before object is being created.

Suppose I have a class User

class User << ActiveRecord::Base
  has_many :subjects, after_add: :create_user_subject

  def create_user_subject
    Subject.create!(user_id: self.id,......) 
  end
end 

So when I am trying to create user object.

user = User.new(name: 'some name')
user.save

then it is throwing an error

OCIError: ORA-01400: cannot insert NULL into ("subjects"."user_id")

Why it is trying to save an association subjects before user object is created. It was working in rails 3 why the functionality is changed in rails 5 and what are the alternatives. Thanks

How to generate swagger without writing spec files

I am looking for a gem which will generate swagger doc and showed it on the swagger ui, I came across rswag gem but it requires spec file needs to be present for generating the swagger doc

Is there any gem that will auto generate swagger doc if I put it in on the API controller?

Ransack on enum filter for dropdown list

class Schedule < ApplicationRecord 
  belongs_to :event
  enum county: {USA: 0, INDIA: 1, Brasil: 2}
end

ransack select in index.erb.html

<%= f.collection_select :schedules_county_matches_all, Schedule.counties.map{ |dp| [dp.first, dp.first.humanize] }, :first.to_s, :second ,:include_blank => "All"%>

which gives output select dropdown list but not value as in Postgres database the value stored as integer not string

<li class=""><span>All</span></li>
<li class=""><span>USA</span></li>
.......

As working filter, I guess in view it should be added value in li

<li value=""><span>All</span></li>
<li value="0"><span>USA</span></li>
.......

Ruby: Using a regular expression to find some IP address in text file?

I have text file content some logs inside it there are some private IP address , I need to find all those IPs by Using regular expression or if there are other ways i can use ?

file.txt

172.31.255.2 Jan 22 20:29:55 local0 info 1 2019 Jan 22 17:29:54 ANK-IGW_LC7_Internet1 - - NAT44 - [SessionbasedAD 6 10.194.97.168 internet1 - 185.106.28.145 19691 15821 - 185.60.216.35 443 ][SessionbasedAD 6 10.194.97.168 internet1 - 185.106.28.145 57156 29896 - 185.60.216.11 443 ][SessionbasedAD 6 10.193.1.203 internet1 - 185.106.28.121 43201 9340 - 146.0.239.19 443 ][SessionbasedAD 17 10.191.35.247 internet1 - 185.106.28.169 22729 11691 - 93.91.201.207 53 ][SessionbasedAD 6 10.191.5.249 internet1 - 185.106.28.97 5541 56078 - 95.170.215.120 80 ][SessionbasedAD 6 10.191.8.140 internet1 - 185.106.28.73 4319 15989 - 5.129.235.102 55820 ][SessionbasedAD 6 10.195.0.168 internet1 - 185.106.28.1 36823 47893 - 216.58.212.46 443 ][SessionbasedAD 17 10.194.131.2 internet1 - 185.106.28.49 54713 43535 - 212.237.115.209 443 ][SessionbasedAD 6 10.193.1.179 internet1 - 185.106.28.145 47574 8226 - 130.193.149.19 443 ][SessionbasedAD 17 10.191.192.220 internet1 - 185.106.28.121 16709 49433 - 93.91.201.207 53 ][SessionbasedAD 6 10.193.1.179 internet1 - 185.106.28.145 35656 47013 - 130.193.149.11 443 ][SessionbasedAD 17 10.191.8.140 internet1 - 185.106.28.73 15989 25885 - 39.42.98.88 62066 ][SessionbasedAD 6 10.194.99.170 internet1 - 185.106.28.1 39010 9907 - 172.217.169.180 443 ][SessionbasedAD 6 10.195.8.136 internet1 - 185.106.28.193 39866 56438 - 212.237.115.33 443 ] 172.31.255.2 Jan 22 20:29:55 local0 info 1 2019 Jan 22 17:29:54 ANK-IGW_LC7_Internet1 - - NAT44 - [SessionbasedAD 6 10.191.7.99 internet1 - 185.106.28.161 3471 9214 - 130.193.149.17 80 ][SessionbasedWD 6 10.195.3.115 internet1 - 185.106.28.65 4021 46771 - 216.239.36.126 443 ][SessionbasedWD 6 10.191.4.152 internet1 - 185.106.28.209 45775 3524 - 88.85.66.146 443 ][SessionbasedWD 17 10.191.100.160 internet1 - 185.106.28.41 26447 13671 - 93.91.201.207 53 ][SessionbasedAD 6 10.191.7.99 internet1 - 185.106.28.161 54379 27461 - 130.193.149.8 80 ][SessionbasedWD 6 10.193.2.24 internet1 - 185.106.28.209 1525 58284 - 80.67.85.29 443 ][SessionbasedWD 6 10.193.2.24 internet1 - 185.106.28.209 48488 42817 - 80.67.85.29 443 ][SessionbasedWD 6 10.193.2.24 internet1 - 185.106.28.209 48486 59626 - 80.67.85.29 443 ][SessionbasedWD 6 10.193.2.24 internet1 - 185.106.28.209 48494 22776 - 80.67.85.29 443 ][SessionbasedWD 6 10.195.5.37 internet1 - 185.106.28.65 6493 51461 - 185.60.216.52 443 ][SessionbasedWD 17 10.194.100.133 internet1 - 185.106.28.113 63561 17683 - 119.28.52.85 8011 ][SessionbasedWD 6 10.193.6.28 internet1 - 185.106.28.17 54066 20671 - 185.60.216.19 443 ][SessionbasedWD 6 10.195.5.117 internet1 - 185.106.28.209 1893 5015 - 212.237.115.33 443 ][SessionbasedWD 6 10.194.130.163 internet1 - 185.106.28.65 36203 65366 - 172.217.169.162 443 ][SessionbasedWD 6 10.191.5.233 internet1 - 185.106.28.41 50332 25093 - 185.60.216.19 443 ]


for example i have to find IPs start with 10.191 || 10.192 || 10.193 ||10.194

For Now i am using the below code to find specific IP ruby.file

file_path = './file.txt'
string = '10.195.0.168'
File.open(file_path) do |f|
    f.readlines.each { |line|
        if line[string]
            puts line
            puts string
        end
    }
end

vendredi 25 janvier 2019

Currently on Rails 3, starting to write unit tests, so is it better to go with Rspec or Minitest given the future of Rails 6 and unit testing?

I need advice. Our software is currently on Rails 3 and we're starting to write unit tests, but we can't decide whether to go with RSpec or Minitest. we're considering to go with RSpec purely over the fact that some of us have experience in it (slight bias included) and that we like the look of it better, syntactically.

But as we're considering future-proofing out software for when we upgrade the Rails versions. As Minitest comes as a default with Rails 5, it seems like the community is turning to Minitest over Rspec for that reason (but not 100% certain if that's the case). With Rails 6 coming in April, it seems all the more reason with go with MiniTest is because new ability to parallel test.

Do you think it's better to go with MiniTest over RSpec, or do you think Rspec will be able to compete with MiniTest still?

On mousedown event firing twice how can i stop it

I have working on ruby project and using coffee-script there is one case where I use mousedown event.

$(document).on 'mousedown', @Selector(), (event)->  
    console.log('testing')

When I click on element the then it firing twice and print testing more then once. So how can i resolve this issue.

Rails link_to tag do not change the url in the browser

I am using Rails 5 with ruby 2.4
I have few statements wirtten on the view page with the link_to tag when I click on the link_to tag the it redirect me to the next page but don the change the URL this is very strange for me here is my view page.

<div class="container">
  <%= render "shared/breadcrumb" %>
  <%= render "shared/back_button" %>
  <h2>Cader</h2>
  <div id="data_conversion_request">
    <div class="row">
      <% unless @job.nil? %>
        <div class="row">
          <div class="col-md-12">
            <table class="table">
              <thead>
              <tr>
                <th scope="col" colspan="4">
                  You have checked out a job on <%= @job.bucket.created_at.strftime("%m/%d/%Y %I:%M %p") %>
                </th>
              </tr>
              </thead>
              <tbody>
              <tr>
                <th scope="row">Job ID</th>
                <th><%= @job.id %></th>
              </tr>
              <tr>
                <th scope="row">CLient</th>
                <th><%= @job.user.full_name %><th>
              </tr>
              <tr>
                <th scope="row">Email</th>
                <th><%= @job.user.email %><th>
              </tr>
              <tr>
                <th scope="row">Client Company</th>
                <th><%= @job.user.address.company_institute_name %></th>
              </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="row">
          <div class="col-md4"></div>
          <div class="col-md4"></div>
        </div>
        <div class="row">
          <div class="col-md4"></div>
          <div class="col-md4"></div>
        </div>
        <div class="row">
          <div class="col-md-2 col-md-offset-1" style="background:lightgreen">
            <h3>Job tools</h3>
          </div>
        </div>
      <% end %>
      <ul class="list-group">
        <% if @job.nil? %>
          <li class="list-group-item">
            <%= link_to 'Check out job', cader_available_job_path, class: '', title: 'check in an available job', data: {toggle: 'tooltip'} %>
          </li>
        <% else %>
          <li class="list-group-item">
            <%= link_to 'Check in a job', cader_check_in_job_path(:job_id => @job.id), class: 'btn btn-link', title: 'checkin job', data: {toggle: 'tooltip'} %>
          </li>
          <li class="list-group-item">
            <%= link_to 'Release a job', cader_release_job_path(:job_id => @job.id), class: 'btn btn-link', title: 'release job', data: {toggle: 'tooltip'} %>
          </li>
          <li class="list-group-item">
            <!--            <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>-->
            <%= button_tag 'Download files', class: "btn btn-link", onclick: "job_files(#{@job.id})", data: {toggle: 'modal', target: '#files'} %>
            <%#= link_to 'Download files', cader_downloads_path(:job_id => @check_cader[0].job_id), class: '', title: '', data: {toggle: 'tooltip'} %>
          </li>
          <li class="list-group-item">
            <%= button_tag 'History', class: "btn btn-link", onclick: "history(#{@job.id})", data: {toggle: 'modal', target: '#history'} %>
            <%#= link_to 'History', cader_history_path(:job_id => @check_cader[0].job_id),class: '', title: 'Job History', data: {toggle: 'tooltip'} %>
          </li>
        <% end %>
      </ul>
      <div> System Tools</div>
      <ul>
        <!--        <li class="list-group-item">-->
        <%#= link_to 'Customer profile', 'javascript:void(0)', class: '', title: '', data: {toggle: 'tooltip'} %>
        <!--        </li>-->
        <!--        <li class="list-group-item">-->
        <%#= link_to 'Messages', 'javascript:void(0)', class: '', title: '', data: {toggle: 'tooltip'} %>
        <!--        </li>-->
        <!--        <li class="list-group-item">-->
        <%#= link_to 'Queue Status', 'javascript:void(0)', class: '', title: '', data: {toggle: 'tooltip'} %>
        <!--        </li>-->
        <li class="list-group-item">
          <%= link_to 'Job folder', cader_job_folder_path, class: '', title: '', data: {toggle: 'tooltip'} %>
        </li>
        <!--        <li class="list-group-item">-->
        <%#= link_to 'Reset timer', 'javascript:void(0)', class: '', title: '', data: {toggle: 'tooltip'} %>
        <!--        </li>-->
        <!--        <li class="list-group-item">-->
        <%#= link_to 'Recent Jobs', 'javascript:void(0)', class: '', title: '', data: {toggle: 'tooltip'} %>
        <!--        </li>-->
      </ul>
    </div>
  </div>
  <div id="checklist_data_conversion" style="display: none;"></div>
</div>

<!-- Modal -->
<div id="files" class="modal fade" role="dialog">
</div>

<!-- Modal 2 -->
<div id="history" class="modal fade" role="dialog">
</div>


<script type="text/javascript">

    <% unless @job.nil? %>

    function history(id) {
        // console.log('Reached');
        $.ajax({
            type: "GET",
            url: "<%= cader_history_path(:job_id => @job.id) %>",
            data: {"id": id},
            dataType: 'html',
            success: function (data) {
                $('#history').html(data);
                // console.log('success');
            },
        });
    }

    function job_files(id) {
        // console.log('Reached');
        $.ajax({
            type: "GET",
            url: "<%= cader_downloads_path(:job_id => @job.id) %>",
            data: {"id": id},
            dataType: 'html',
            success: function (data) {
                $('#files').html(data);
                // console.log('success');
            },
        });
    }

    <% end %>

</script>

But the same link_to tag is working fine for rest of the pages in the application, please correct when is written incorrect inside the page or is there any other way to write the link_to tag.

jeudi 24 janvier 2019

AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action

I've tried suggested different options in different tickets but nothing worked out me and getting this error

AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".)

Can you please let me know what is wrong in this code

def show
es = @external_search

if es.search_type == 'internal' && ['json','xml'].include?(params[:format])
  rs = @external_search.resume_search
  smws = rs.connection.daxtra_smws
  dax_xml_resp = RestClient.post(smws.hostaddress__c + 'ws/dispatch',es.request_input,{:content_type => 'text/xml',  :accept => 'application/xml', :timeout=> 90})

  cIds = []
  cHash = Hash.new
  results = []

  search_results = process_results(dax_xml_resp)
  cIds = cIds.concat(search_results[:candidate_ids]).uniq
  cHash = cHash.merge(search_results[:hash])
  results = results.concat(search_results[:results]).uniq unless search_results[:results].nil?
  if(!es.match_vacancy_id.blank?)
    match_results = search_results
  end
  #if !es.match_vacancy_id.nil?
    #match_results = process_results(es.daxtra_match_vacancy[:response].body) rescue nil
    #unless match_results.nil?
      #cIds = cIds.concat(match_results[:candidate_ids]).uniq
      #cHash = cHash.merge(match_results[:hash])
      #results = results.concat(match_results[:results]).uniq unless match_results[:results].nil?
    #end
  #end

  resume_results = []
  fields_needed = []

  if !es.fields_to_select.blank?
    fields_needed = ['Id','TR1__External_Candidate_Id__c']
    fields_needed.push(es.fields_to_select.to_s.split(','))
  end


  unless results.nil?
    tr_contacts = []
    cIds.in_groups_of(1000){|group|
      processed_group = group.compact.reject(&:blank?)
      #tr_contacts += rs.connection.soap(rs.session_id).find_where('Contact', TR1__External_Candidate_Id__c: processed_group, ["Id", "FirstName", "CreatedBy"]).records

      if !fields_needed.blank?
        tr_contacts += rs.connection.soap(rs.session_id).find_where('Contact', {'TR1__External_Candidate_Id__c' => processed_group} , fields_needed.uniq)
        else
        tr_contacts += rs.connection.soap(rs.session_id).find_where('Contact', {'TR1__External_Candidate_Id__c' => processed_group})
      end
    }

    tr_contacts.each {|x|
      cHash[x.TR1__External_Candidate_Id__c]["Result"]["Score"] =  "#{cHash[x.TR1__External_Candidate_Id__c]["Result"]["Score"].to_i.round}%"
      cHash[x.TR1__External_Candidate_Id__c]["Result"]["badges"] =  [{:name => 'match', :text_color => 'blue', :color => 'grey'}] if !match_results.nil? && match_results[:candidate_ids].include?(x.TR1__External_Candidate_Id__c)
      resume_result = Hash["tr-object" => x.to_hash, "match-attributes" => cHash[x.TR1__External_Candidate_Id__c]["Result"].merge({"daxtra" => cHash[x.TR1__External_Candidate_Id__c]["Result"]})]
      resume_results << resume_result
      }
  end


  if resume_results.blank?
      es.status_line1 = "<strong>#{es.name}</strong>"
      es.retry = 0
      es.result_count = 0
    else
      es.status_line1 = "<strong title='#{resume_results.size} Result(s)'>#{es.name}</strong>"
      es.result_count = resume_results.size
      es.retry = 0
  end
  es.status_line2 = "<div title='[Ref:#{es.id}] #{es.message}'>Status: <strong>Ready</strong></div>"

  #h = Hash["a" => 100, "contact-array" => ca]
  response_hash = {:ResumeSearch=>{:Status=>{:Code=>"100", :Description=>"OK"}, :data=>{:result=> resume_results}}}

  #rs.connection.soap(rs.session_id).update('TR1__ResumeSearch__c', Id: rs.id, TR1__result_url__c: request.fullpath) #TakingTooMuchTime

  respond_to do |format|
    format.html { render :text => parsed_xml }
    #format.html { render :text => h.to_json }
    format.xml { 
      store_return_to
      render :xml => parsed_xml }
    format.json { 
      store_return_to
      render json: response_hash.to_json }
  end

end

 if es.search_type == 'external' && ['json','xml'].include?(params[:format])

  url = "https://#{es.host}/jwb/dispatch?db=#{es.database}&handle=#{es.request_id}&action=search_results"
  ext_search = RestClient.get(url, :timeout => REST_TIMEOUT)
  response = JSON.parse(ext_search)
  plain = Base64.decode64(response['results'])
  dresjson = Hash.from_xml(plain)
  json_out = dresjson.to_json
  if JSON.parse(json_out)['ZZ']['cv_entry'].class == Hash
    new_json = car = {:ZZ => {:cv_entry => [JSON.parse(json_out)['ZZ']['cv_entry']]} }
    json_out = new_json.to_json
  end
  result_count = JSON.parse(json_out)['ZZ']['cv_entry'].size  unless json_out.blank? #rescue nil

  es.status_line2 = "<div title='#{es.message}'>Status: <strong>Ready</strong></div>"

  if !result_count.nil?
    es.status_line1 = "<strong title='#{es.name} - #{result_count} Result(s)'>#{es.name}</strong>"
    es.result_count = result_count
  end

  es.status_line2 = "<div title='[Ref:#{es.id}] #{es.message}'>Status: <strong>Ready</strong></div>"
  respond_to do |format|
    #format.html { render :text => response }
    #format.html { render :text => tr_contacts }
    format.xml { render :xml => plain }
    format.json { render json: json_out }
  end
 end
 es.save
 es.to_intercom

end

Thanks

How to use faker gem to generate fake food names?

I have read up several tutorials, but I am still unsure how to do what I want, therefore I am sorry if it sounds dump. I have an active record called "Sandwitches", which has as attributes: name, price and availability. As I want to generate fake data for it, I am not quite sure how I can achieve something like this, because the name attribute faker can generate stands for names of persons. I would like for instance to generate names for the sandwitches, like "Club Sandwitch" or "Pesto with Feta Cheese". Is there anyway to do this with faker gem ? Or basically could I use any other gem to achieve that?

I apppreciate any help you can provide!

To compile ruby program with rails project

I have a plan to create a Rails web project. The Project is like compile ruby programs and to give output. for this I have no idea where to compile ruby programs.

Migration in Rails gives back could not find table error

I made a new migration in order to add a price column in my Ingredients Active Record. Despite that when I run rails db:migrate I get an error saying that the table ingredients does not exist. Here are my console commands:

 C:\Users\andri\Desktop\hoagieShop\hoagieShop>rails generate migration 
 AddPriceToIngredients price:decimal, false:null --force
  invoke  active_record
  remove    db/migrate/20190124075954_add_price_to_ingredients.rb
  create    db/migrate/20190124080657_add_price_to_ingredients.rb

C:\Users\andri\Desktop\hoagieShop\hoagieShop>rails db:migrate
== 20190123201200 RemovePriceFromIngrendients: migrating 
======================
-- remove_column(:ingrendients, :price, :decimal)
rails aborted!
StandardError: An error has occurred, this and all later migrations 
canceled:
Could not find table ingrendients 
C:/Users/andri/Desktop/hoagieShop/hoagieShop/db/migrate/201901232 
01200_remove_price_from_ingrendients.rb:3:in change
bin/rails:4:in require
bin/rails:4:in <main>

Caused by:
ActiveRecord::StatementInvalid: Could not find table ingrendients


C:/Users/andri/Desktop/hoagieShop/hoagieShop/db/migrate/20190123201200_
remove_pr 
ice_from_ingrendients.rb:3:in change
bin/rails:4:in require
bin/rails:4:in <main>
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

I have removed and added this migration again a few times so I am not sure if this plays any role. Does anyone have an idea as to why this happens? I appreciate any help!

mercredi 23 janvier 2019

Fails to provide a default value for the 3rd argument in Ruby

def input_to_index(space)
  input = space.to_i - 1
end    

def move(board, index, character = "X")
  input_to_index(board)
  return board
end

I'm working through a beginner ruby course online and the code above returns an error saying that the 3rd argument isn't given a default value of string X.

Am I missing something simple here???

I've been going crazy trying to solve this.

Thanks!

How to check value null in ruby on rails 3?

I have create new array jobs and j.id is start from 423 and loop creates array from 0 to total job ids with null value from 0 to 422 id. So my question is how to set condition to check the null value of j.name?

@jobs = []
demo.demojobs.each do | j |
    if j.name != null #condition 
        @jobs[j.id] = j.name
    end
end 

Working with rails version 3.2.11

mardi 22 janvier 2019

Rails, Geo-Search using Google map API

@room_address = Room.near("any location");

I am trying to list rooms (from database) located in the searched location. this line is returning error:

Unsupported argument type: 0 (Fixnum)

tried using different set of parameters. But always returns the same error. How to fix this? following is the schema for Rooms

create_table "rooms", force: :cascade do |t|
t.string   "listing_name"
t.text     "summary"
t.string   "address"
t.integer  "price"
t.boolean  "active"
t.integer  "user_id"
t.datetime "created_at",   null: false
t.datetime "updated_at",   null: false
t.float    "latitude"
t.float    "longitude"
t.index ["user_id"], name: "index_rooms_on_user_id"
end

How to push an object into ActiveRecord::Relation in rails 5

I am stuck in weird situtaion, I am working on upgrading an existing rails 3 appliction to rails 5 app.

Using rails 3, I have an object report which has many organizations

@report.organizations
#<ActiveRecord::Relation [#<Organization id: 1, name: "Org 1", description: nil, created_at: "2012-01-27", updated_at: "2019-01-15">]>
@report.organizations.count    # 1

when I push a new org object into existing activerecord relation it gives me new activerecord relation including new org

@report.organizations<< Organization.new
[#<Organization id: 1, name: "Org 1", description: nil, created_at: "2012-01-27", updated_at: "2019-01-15">, #<Organization id: nil, name: nil, description: nil, created_at: nil, updated_at: nil>]
# Getting count
@report.organizations.count    # 2

Using rails 5, I am getting exception

@report.organizations << Organization.new
*** NoMethodError Exception: undefined method `<<' for #<Organization::ActiveRecord_Relation:0x00007f93483e2640>

and when I do like

@report.organizations.to_a << Organization.new

it gives me

[#<Organization id: 1, name: "Org 1", description: nil, created_at: "2012-01-27", updated_at: "2019-01-15">, #<Organization id: nil, name: nil, description: nil, created_at: nil, updated_at: nil>]

but count is stil 1 instead of two

@report.organizations.count    # 1

Hope my issue is clear to you, please help me how to fix this issue. Thanks

lundi 21 janvier 2019

Apache SSL: httpd (no pid file) not running

When I want to start apache there is httpd (no pid file) not running. More below.

  • http worked for some years. I want ssl now.
  • it is a ruby on rails application

  • in /etc/apache2/ssl I put cacert.crt, ***.pem, intermedi**.crt, key.pem, req.pem, rootcert.crt

  • I tested the following:

The <VirtualHost *:80> is in the file /etc/apache2/vhosts.d/default.conf and when I make a permanent redirect to <VirtualHost *:443>(which is in the same file below the <VirtualHost *:80> I get after I try service apache2 restart:

Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details.

journalctl -xe

Jan 21 13:00:01 myserver CRON[13699]: pam_unix(crond:session): session 
closed for user root
Jan 21 13:02:27 myserver liblogging-stdlog[1089]: -- MARK --
Jan 21 13:15:01 myserver cron[13735]: pam_unix(crond:session): session 
opened for user root by (uid=0)
Jan 21 13:15:01 myserver systemd[1]: Started Session 36832 of user root.
-- Subject: Unit session-36832.scope has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit session-36832.scope has finished starting up.
--
-- The start-up result is done.
Jan 21 13:15:01 myserver dbus[1064]: [system] Activating service         name='org.opensuse.Snapper' (using servicehelper)
Jan 21 13:15:01 myserver dbus[1064]: [system] Successfully activated     service 'org.opensuse.Snapper'
Jan 21 13:15:03 myserver CRON[13735]: pam_unix(crond:session): session     closed for user root
Jan 21 13:22:21 myserver dbus[1064]: [system] Activating via systemd:     service name='org.freedesktop.hostname1' unit='dbus-    org.freedesktop.hostname1.service'
Jan 21 13:22:21 myserver systemd[1]: Starting Hostname Service...
-- Subject: Unit systemd-hostnamed.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit systemd-hostnamed.service has begun starting up.
Jan 21 13:22:21 myserver dbus[1064]: [system] Successfully activated     service 'org.freedesktop.hostname1'
Jan 21 13:22:21 myserver systemd[1]: Started Hostname Service.
-- Subject: Unit systemd-hostnamed.service has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit systemd-hostnamed.service has finished starting up.
--
-- The start-up result is done.
Jan 21 13:30:01 myserver cron[15546]: pam_unix(crond:session): session     opened for user root by (uid=0)
Jan 21 13:30:01 myserver systemd[1]: Started Session 36833 of user root.
-- Subject: Unit session-36833.scope has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit session-36833.scope has finished starting up.
--
-- The start-up result is done.
Jan 21 13:30:01 myserver CRON[15546]: pam_unix(crond:session): session     closed for user root
Jan 21 13:31:48 myserver systemd[1]: Starting The Apache Webserver...
-- Subject: Unit apache2.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit apache2.service has begun starting up.
Jan 21 13:31:48 myserver start_apache2[15591]: [Mon Jan 21 13:31:48.530416     2019] [so:warn] [pid 15591] AH01574: module socache_shmcb_module is already     loaded, skipping
Jan 21 13:31:48 myserver systemd[1]: apache2.service: Main process exited,     code=exited, status=1/FAILURE
Jan 21 13:31:48 myserver start_apache2[15600]: [Mon Jan 21 13:31:48.671071     2019] [so:warn] [pid 15600] AH01574: module socache_shmcb_module is already     loaded, skipping
Jan 21 13:31:48 myserver start_apache2[15600]: httpd (no pid file) not     running
Jan 21 13:31:48 myserver systemd[1]: Failed to start The Apache Webserver.
-- Subject: Unit apache2.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit apache2.service has failed.
--
-- The result is failed.
Jan 21 13:31:48 myserver systemd[1]: apache2.service: Unit entered failed     state.
Jan 21 13:31:48 myserver systemd[1]: apache2.service: Failed with result     'exit-code'.

When I take out the lines below and the <VirtualHost *:443> then it works again on http.

SSLEngine on
SSLCertificateFile /etc/apache2/ssl/***.pem
SSLCertificateKeyFile /etc/apache2/ssl/key.pem
SSLCertificateChainFile /etc/apache2/ssl/intermediatecacert.crt
SSLCACertificateFile /etc/apache2/ssl/cacert.crt

Any ideas?

Datatable with server-side processing with check-boxes (Rails)

I have replace a dataTable on rails that was working perfectly well, with check-boxes to select rows and send them to another page. Due to the size of the table (>20,000) I was told to use server-size processing.

I have build the table, and manage to load my data within a second, all good. Search function, filtering etc all work. I display the check-boxes with no problem.

My view:

<div class="col-md-12">
  <table id="distrib_table" class="table table-striped" data-source="<%= distribs_url(format: "json") %>">
    <thead>
    <th scope="col"></th>
    <th scope="col"> First Name</th>
    <th scope="col"> Last Name</th>
    <th scope="col"> Email</th>
    <th scope="col"> Company</th>
    <th scope="col"> Ind. Delete</th>
    </thead>
    <tbody>


    </tbody>

  </table>
</div>
<script>

    $(document).ready(function (){
        var table = $('#distrib_table').DataTable({
            "searching": true,
            "limit": 5,
            "lengthMenu": [[5, 10, 25, 50, 100, 250, -1], [5, 10, 25, 50, 100, 250, "All"]],
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": $('#distrib_table').data('source'),
            'columnDefs': [{
                'targets': 0,
                'searchable':false,
                'orderable':false,
                'className': 'dt-body-center',
                'render': function (data, type, full, meta){
                    return '<input type="checkbox" name="id[]" value="'
                        + $('<div/>').text(data).html() + '">';
                }
            }],
            'order': [1, 'asc']
        });

        // Handle click on "Select all" control
        $('#distrib_table').on('click', function(){
            // Check/uncheck all checkboxes in the table
            var rows = table.rows({ 'search': 'applied' }).nodes();
            $('input[type="checkbox"]', rows).prop('checked', this.checked);
        });

        // Handle click on checkbox to set state of "Select all" control
        $('#distrib_table tbody').on('change', 'input[type="checkbox"]', function(){
            // If checkbox is not checked
            if(!this.checked){
                var el = $('#distrib_table-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;
                }
            }
        });

        $('#distrib_table').on('submit', function(e){
            var form = this;

            // Iterate over all checkboxes in the table
            table.$('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)
                        );
                    }
                }
            });

            // FOR TESTING ONLY

            // Output form data to a console
            $('#distrib_table').text($(form).serialize());
            console.log("Form submission", $(form).serialize());

            // Prevent actual form submission
            e.preventDefault();
        });
    });
</script>

my controler:

class DistribsController < ApplicationController
  before_action :authenticate_user!, except: [:index, :show, :new, :edit_multiple, :update_multiple]
  before_action :find_distrib, only: [:show, :edit, :update, :destroy]
  respond_to :html, :json

  def index
    respond_to do |format|
      format.html {}
      format.json {render json: DistribsDatatable.new(view_context)}
    end

  end

  def show
    @distribs = Distrib.all.order("created_at DESC")

  end

  def new
    @distrib = current_user.distribs.build
  end

  def edit
    @distrib = Distrib.find params[:id]

  end

  def destroy
    @distrib = Distrib.find params[:id]
  end

  def distrib_params
    params.require(:distrib).permit(:first_name, :last_name, :email, :user_id)
  end

  def update
    @distrib = Distrib.find params[:id]
    @groups = Group.where(user_id: current_user.id)


    respond_to do |format|
      if @distrib.update(distrib_params)
        format.html {redirect_to(@distrib, :notice => 'Updated was successfull.')}
        format.json {respond_with_bip(@distrib)}
      else
        format.html {render :action => "edit"}
        format.json {respond_with_bip(@distrib)}
      end

    end
  end

  def create
    @distrib_ids = params[:selected_distribs]
    @groups = Group.where(user_id: current_user.id)

    @distrib = current_user.listdedistributions.build(listdedistribution_params)
    if @distrib.save
      redirect_to distribs_path
    else
      render 'new'
    end
  end

  def edit_multiple
    @distribs = Distrib.find(params[:distrib_ids])
    puts("Edit multiple", @distribs)
  end

  def find_distrib
    @distrib = Distrib.find(params[:id])
  end

  def listdedistribution_params
    params.require(:listdedistribution).permit(:distrib_id, :user_id, :group_id, :origine)
  end
  def group_params
    params.permit(:name, :user_id, :description)
  end
end

I would like to be able to fix the following issues:

  1. Checked box disappear when navigating from one page to the other,
  2. I could not put a select ALL check box on top the column,
  3. I no longer have a button to validate the selected boxes to pass the them to edit_multiple.html.erb

How to set dropdown select through data-attribute or text?

I am working on a JavaScript function which should copy shipping address form values to a billing address form section in case both are identical.

I wanted to rely either on a data attribute, text or innerHTML to set the select, since option id changes once a selection has been made.

<select id="order_bill_to_land" name="order[bill_to_land_id]"><option value="">select a country</option>
  <option value="1" data-land="1">Afghanistan</option>
  <option value="2" data-land="2">Aland Islands</option>
  <option value="3" data-land="3">Albania</option>

My JavaScript function is:

let land = document.querySelector("#country").getAttribute('data-country');
let bl = document.querySelector("#order_bill_to_land");

for (let i = 0; i < bl.options.length; i++) {
  if (bl.options[i].text === land) {
    return console.log("if loop working");
    bl.selectedIndex = i;
    break;
  };
}

Which produces 0, because the if conditional does not work which I deduce from the fact that I am unable to log to console.

Why is that so?

I found a shorter version for selecting the selectedIndex:

bl.selectedIndex = [...bl.options].findIndex (option => option.innerHTML === land);

but it produces -1. Since it is so nicely condensed I am unable to find out why it does not work.

How can I get this working?

Thank you in advance!

Rails: How does index option work for form select?

I am working on a checkout process where I have a shipping address and billing address. When both are identical the shipping address data is copied in the client through JavaScript into the billing address.

I have a problem with a select dropdown field, which displays a prompt on first load and invites to choose the billing country.

<%#= f.collection_select(:bill_to_land_id, Land.all, :id, :name, {:prompt => "select a country"}, {:id => 'order_bill_to_land'}) %>

Apparently, following the API documentation on FormOptionsHelper, I cannot rely currently on the index of the select option, since after choosing the billing country, navigating in the checkout process and returning to the billing address section the index count changed. This happens probably because the prompt is not displayed any longer.

:prompt - set to true or a prompt string. When the select element doesn’t have a value yet, this prepends an option with a generic prompt – “Please select” – or the given prompt string.

The main difference is that if the select already has a value, then :prompt will not show whereas the :include_blank always will.

<select id="order_bill_to_land" name="order[bill_to_land_id]"><option value="">select a country</option>
  <option value="1">Afghanistan</option>
  <option value="2">Aland Islands</option>
  <option value="3">Albania</option>

<select id="order_bill_to_land" name="order[][bill_to_land_id]"><option value="1">Afghanistan</option>
  <option value="2">Aland Islands</option>
  <option value="3">Albania</option>

Is there a way to maintain the prompt even after a value has been selected in order to still rely on the selectedIndex method in JS? I know there is an index option for select helper, but cannot find any documentation.

samedi 19 janvier 2019

How to know which function is used

I have problem how to know which function is used, cause here is multiple implementation. How rails know which function is correct. How you solve this problem in Ruby, is there way to tell IDE which function will be used

https://imgur.com/JZxD3eo

i need to get a user id from a query result

am querying from my User table using the user name, how do i get the user id from the query object User.where(user_name: "john")

my goal is to get the User id: 5, i thought it was as easy as (.id), but thats not working

=> #<ActiveRecord::Relation [#<User id: 5, user_name: "john", user_city: "India", created_at: "2019-01-19 18:02:32", updated_at: "2019-01-19 18:02:32">]> 

vendredi 18 janvier 2019

why is memory occupied by Active record object less than the hash form of that record?

By using ObjectSpace.memsize_of() in rails, i noticed active record object occupies lesser space than hash. Ex : Say a = User.last , b = a.attribues, c = a.json .
I got ObjectSpace.memsize_of(a) < ObjectSpace.memsize_of(b) ObjectSpace.memsize_of(c). why is this and how is it possible ?

jeudi 17 janvier 2019

How to fix Rails Schema file being auto edit after rake db:migrate

We have always had some issues with rails schema file. It got worse after upgraded from rails 3 to rails 4.2. So everytime someone runs "db: migrate" on the local machine, it adds, removes or edit stuff in the schema file. Nothing got affected in the database though.

When we were on Rails3, we got changes like string limit: 255 changes to 100, columns removed and added back in a different row. In Rails 4, apart from the pre-existing ones, we got all the timestamp (created_at, updated_at) added with null: false. We don't set up the default for timestamp in migration files. Also, the index names are changed to those rails generated ones, but we do specify the index names and they are sitting in the database without any issue.

Now it gets really annoying as it causes conflicts on and making noise. Any suggestion to fix this?

User Rails 4.2.10, Ruby 2.5.3, mysql version 5.7.22 by Homebrew.

DRY Pagination for complex POST action

I implemented a stats panel in my current project. It's possible to select people by specific objects (different Models) which allows you for example to search for people which belong to in Group B, Organisation A and Flag A (Group B ∩ Organisation A ∩ Flag A; btw. it's possible to select multiple objects of the same class).

This makes my post-request very complex and has many parameters (sorting, fields, ...). The result is then displayed via jQuery in a special div.

What would be the best practice to make my project more flexible in order to support a page_id via the rails routes.

First I thought about hashing all the parameters in order to support absolute urls without form fields and then adding the page number (e.g. /stats_search/param_hash/2 ).

Well, to be short: I want a DRY and clean solution (without passing all my form fields again) in order to support multiple pages for a specific POST request (group selection) via GET requests.

mercredi 16 janvier 2019

How to pass query params in form-data in rails link_to instead of appending it in url?

I have a page which displays the transaction search results and i have a search filter based on one column(Token) upon clicking this the search criteria should be set and the search params should be passed as a form-data in post method. but currently, it is getting appended to the URL. Kindly, help meSearch results

search based on token

_payment_transaction.html.erb

    <div class="block">

  <% if @transactions_exceed_limit %>
    <div class="row">
      <div class="block-title" id="max-fetch-results-message">
        <h4 class="text-primary">Your search returned too many results, so only the first <%=
          TransactionSearchController::MAX_FETCH_SIZE %> results have been displayed.</h4>
      </div>
    </div>
  <% end %>

  <div class="row" style="width:100% !important;">
    <div class="col-md-4">
      <div class="block-title">
        <% if @integratedApi == false %>
          <h3><strong> <%= @transactions.count %> results found</strong></h3>
          <%else %>
        <h3><strong> <%= @total_records %> results found</strong></h3>
          <%end %>
      </div>
    </div>

    <div class="col-md-8">
      <div id="csvButton">
        <%= form_tag(csv_path(params.except('controller', 'action').merge(format: "csv")), method: "post") do %>
          <%= submit_tag "Download CSV", class: 'btn btn--charcoal-ghost', id: 'download_csv' %>
        <% end %>
      </div>
    </div>
  </div>

  <div class="row" style="margin-bottom: 5px">
    <hr class="line">
  </div>
  <div class="row">
    <div class="table-responsive tb-responsive tble-responsive">
      <table class="table table-condensed table-hover" id="search-result-table" style="margin-left:2%">
        <thead>
        <tr>
          <th>Transaction Id</th>
          <th>Order Id</th>
          <th>Store Id</th>
          <th>Transaction Date</th>
          <th>Transaction Type</th>
          <th>Tender Type</th>
          <th>Token</th>
          <th>Amount</th>
          <th>Currency</th>
          <th>Response </br>Code</th>
        </tr>
        </thead>
        <tbody>
        <% if @integratedApi %>

          <% @transactions.each do |transaction| %>
            <tr>
              <td><%= link_to transaction[:paymentTransactionId], details_path(:id=> transaction), {:remote => true, 'data-toggle' => "modal", 'data-target' => '#modal-window'} %></td>
              <td><%= transaction[:paymentSessionId]%></td>
              <td><%= transaction[:storeId]%></td>
              <td><%= transaction[:createTimestamp].in_time_zone(@timezone).strftime('%B %d, %Y - %l:%M %p') %></td>
              <td><%= @transaction_types[transaction[:transactionType]] %></td>
              <td><%= @tenders[transaction[:tenderType]][1] %></td>
              <td><%= link_to transaction[:paymentAcctUniqueId], params.merge(account_id: transaction[:paymentAcctUniqueId], show_results: "true",clickAccount:"Y"), id: "act_id" %></td>
              <td><%= PaymentsHelper.amount_with_currency_symbol transaction[:transactionAmount], transaction[:isoCurrencyCode]%></td>
              <td><%= transaction[:isoCurrencyCode]%></td>
              <td><%=transaction[:responseCode]%></td>
            </tr>
          <% end %>


          <% else %>
          <% @transactions.each do |transaction| %>

            <tr>
              <td><%= link_to transaction['payment_transaction_id'], details_path(payment_transaction_id: transaction['payment_transaction_id']), {:remote => true, 'data-toggle' => "modal", 'data-target' => '#modal-window'} %></td>
              <td><%= transaction['payment_session_id'] %></td>
              <td><%= transaction['store_id'] %></td>
              <td><%= transaction['create_timestamp'].in_time_zone(@timezone).strftime('%B %d, %Y - %l:%M %p') %></td>
              <td><%= @transaction_types[transaction['transaction_type']] %></td>
              <td><%= @tenders[transaction['tender_type']][1] %></td>
              <% if (@tenders[transaction['tender_type']][0]).in?(['PLCC', 'GC', 'CC', 'CBCC']) %>
                <td><%= link_to transaction['payment_acct_unique_id'], params.merge(account_id: transaction['payment_acct_unique_id'], show_results: "true",clickAccount:"Y"), id: "act_id" %></td>
              <% else %>
                <td><%= transaction['payment_acct_unique_id'] %></td>
              <% end %>
              <% if show_settlement_type? %>
                <td><%= PaymentsHelper.settlement_amount_with_currency_symbol transaction['transaction_amount'], transaction['iso_currency_code'],transaction['settlement_type'] %></td>
              <% else %>
                <td><%= PaymentsHelper.amount_with_currency_symbol transaction['transaction_amount'], transaction['iso_currency_code'] %></td>
              <% end %>
              <td><%= transaction['iso_currency_code'] %></td>
              <% if transaction['transaction_status'] == ('F') %>
                <td>Payment Service Error</td>
              <% else %>
                <td><%= transaction['response_code'] %></td>
              <% end %>
          <% end %>
          </tr>
        <% end %>


        </tbody>
      </table>
    </div>
  </div>


  <div id="modal-window" class="modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
</div>

Search.html.erb

    <script type="text/javascript">
    pt_default_time_gap = <%= ENV['PAYPTL_TRANSACTION_SEARCH_DEFAULT_TIME_GAP_IN_DAYS']%>;
    pt_max_time_gap = <%= ENV['PAYPTL_TRANSACTION_SEARCH_MAX_TIME_GAP_IN_DAYS']%>;
    pt_max_from_date_time_gap = <%= ENV['PAYPTL_TRANSACTION_SEARCH_MAX_TIME_GAP_FROM_CURRENT_DATE_IN_DAYS']%>;
</script>
<% provide(:title, 'Transaction Search') %>
<div id="load"></div>
<% content_for :sub_header do %>
  <%= form_tag({controller: "transaction_search", action: "search"}, method: "post", style: "margin-bottom: 20px;", id: "search_crit_form") do %>
    <%= render "search_criteria" %>

    <div class="row" id="advanced_filters" style="display:none;">
      <%= render "transaction_search/advance_filters" %>
    </div>
  <% end %>
<% end %>
<div id="contents">
<div class="row" style="margin-bottom:5px;margin-top: 15px" id="search_results">

  <div class="search_results_pane" id="search_results_table">
    <% if @transactions.present? %>
      <%= render partial: "transaction_search/payment_transaction", object: @transactions %>
    <% else %>
      <div class="block">
        <div class="block-title" id="emptyResults">
          <h2 class="text-primary"><strong>No Results </strong> Found</h2>
        </div>
      </div>
    <% end %>
  </div>
</div>
  </div>

transaction_search_controller.rb

   require 'base64'
require 'rest-client'
require 'xmlrpc'
require 'nokogiri'
require 'date'
require 'will_paginate/array'

class TransactionSearchController < ApplicationController
  include PaymentsHelper
  include ApplicationHelper
  protect_from_forgery except: :details
  before_filter :authenticate_user!, :can_view_payments_txns?
  before_action :set_store_and_timezone
  before_action :tenders_and_transaction_types, only: [:search, :details]
  before_action :settlement_status, only: [:details]

  DEFAULT_TIME_GAP_IN_DAYS = "#{ENV['PAYPTL_TRANSACTION_SEARCH_DEFAULT_TIME_GAP_IN_DAYS']}".to_i.freeze
  DATE_FORMAT = '%Y/%m/%d %H:%M'.freeze
  SHOW_MOCK_TRANSACTION = ("#{ENV['PAYPTL_TRANSACTION_SEARCH_EXCLUDE_MOCK_TXS']}" == "true").freeze
  PAYMENTS_URI = "#{ENV['PAYPTL_PAYMENT_SERVICE_PROTECT_PAN_URI']}".freeze
  PAYMENTS_USERNAME = "#{ENV['PAYPTL_PAYMENT_SERVICE_PROTECT_PAN_USERNAME']}".freeze
  PAYMENTS_PASSWORD = "#{ENV['PAYPTL_PAYMENT_SERVICE_PROTECT_PAN_PASSWORD']}".freeze
  MAX_FETCH_SIZE = "#{ENV['PAYPTL_TRANSACTION_MAX_FETCH_SIZE']}".to_i.freeze
  MAX_FETCH_SIZE_CSV = "#{ENV['PAYPTL_TRANSACTION_MAX_FETCH_SIZE_CSV']}".to_i.freeze
  TRANSACTION_SEARCH_REST_API_ENABLED_FLAG = "#{ENV['PAYPTL_TRANSACTION_SEARCH_REST_API_ENABLED_FLAG']}"
  PTF_CLIENT_MANAGEMENT_SERVICE_URL = "#{ENV['PAYPTL_PTF_CLIENT_MANAGEMENT_SERVICE_URL']}"

  def search
    @integratedApi=false
    if TRANSACTION_SEARCH_REST_API_ENABLED_FLAG == 'Y'

      @integratedApi=true
      payload = Hash.new
      if params[:per_page].present?
        @selected_per_page = params[:per_page]
      else
        @selected_per_page = 2000
      end
      params[:page] = params[:page] || 1
      payload['storeIds'] = params[:store_ids]

      params[:start_date] = params[:start_date] || Time.now.utc.to_date.days_ago(DEFAULT_TIME_GAP_IN_DAYS - 1).beginning_of_day.strftime(DATE_FORMAT)
      params[:end_date] = params[:end_date] || Time.now.utc.to_date.end_of_day.strftime(DATE_FORMAT)
      payload['startDate'] = params[:start_date]
      payload['endDate'] = params[:end_date]
      payload['pageNum'] = params[:page]
      payload['perPage'] = @selected_per_page
      payload['paymentSessionId'] = params[:payment_session_id] if params[:payment_session_id].present?
      payload['paymentAcctUniqueId'] = params[:account_id] if params[:account_id].present?
      payload['transactionTypes'] = params[:transaction_types] if params[:transaction_types].present?
      payload['tenderTypes'] = params[:tender_types] if params[:tender_types].present?
      payload['transactionStatuses'] = params[:transaction_statuses] if params[:transaction_statuses].present?
      payload['isoCurrencyCode'] = params[:iso_currency_code] if params[:iso_currency_code].present?
      payload['transactionAmount'] = params[:transaction_amount] if params[:transaction_amount].present?
      @transaction_search_results = get_transaction_search_details(PTF_CLIENT_MANAGEMENT_SERVICE_URL + "/payments/transaction/search", payload)
      if @transaction_search_results.present? && @transaction_search_results.kind_of?(Hash) && @transaction_search_results.has_key?(:transactions)
        @total_records = @transaction_search_results[:totalCount]
        @total_records = @total_records.nil? ? 0 : @total_records.to_i
      @transactions = @transaction_search_results[:transactions]
      end
    else
    if @store_list.empty?
      flash.now[:danger] = 'No Store Mapped'
    end


    params[:per_page] = params[:per_page] || 20
    params[:page] = params[:page] || 1
    params[:start_date] = params[:start_date] || Time.now.utc.to_date.days_ago(DEFAULT_TIME_GAP_IN_DAYS - 1).beginning_of_day.strftime(DATE_FORMAT)
    params[:end_date] = params[:end_date] || Time.now.utc.to_date.end_of_day.strftime(DATE_FORMAT)
    results
    end
  end

  def get_transaction_search_details(rest_url, payload)
    begin
      rest_resource = RestClient::Resource.new(rest_url,ENV['PAYPTL_PTF_CLIENT_MANAGEMENT_SERVICE_USER_NAME'], ENV['PAYPTL_PTF_CLIENT_MANAGEMENT_SERVICE_PASSWORD'])
      Rails.logger.debug("Calling Transaction Search URL:#{rest_url}\n Payload:#{payload.to_json}")
      @transaction_search_response = rest_resource.post payload.to_json, :content_type => 'application/json'
       if @transaction_search_response.code == Rack::Utils::SYMBOL_TO_STATUS_CODE[:ok]
        return JSON.parse(@transaction_search_response, :symbolize_names => true)
      else
        Rails.logger.error("Transaction search return status code #{@transaction_search_response.code} for payload #{payload}")
      end
    rescue => e
      Rails.logger.error(e.message)
      flash.now[:danger] = 'Unable to fetch data, Please try later'
    end
  end

  def results
    start_date = Time.strptime(params[:start_date], DATE_FORMAT).utc.beginning_of_day
    end_date = Time.strptime(params[:end_date], DATE_FORMAT).utc.end_of_day

    condition = Hash.new
    @accountId=params[:account_id]
    condition[:store_id] = @store_for_service
    condition[:payment_session_id] = params[:payment_session_id] if params[:payment_session_id].present?
    condition[:transaction_test_ind] = [0, nil] if !SHOW_MOCK_TRANSACTION
    condition[:transaction_type] = params[:transaction_types] if params[:transaction_types].present?
    condition[:transaction_amount] = params[:transaction_amount] if params[:transaction_amount].present?
    condition[:iso_currency_code] = params[:iso_currency_code] if params[:iso_currency_code].present?
    condition[:tender_type] = params[:tender_types] if params[:tender_types].present?
    condition[:transaction_status] = params[:transaction_statuses] if params[:transaction_statuses].present?
    @page=params[:page]
    if(@accountId!=nil && @accountId!='')
      condition[:payment_acct_unique_id] = @accountId
      if(params[:clickAccount]=='Y')
        @page=1
        params[:clickAccount]='N'
      end
    end
    condition[:transaction_status] = params[:transaction_statuses] if params[:transaction_statuses].present?
    if params[:action] == 'csvexport'
      @transactions_export_csv = PaymentTransactionFlat.where(:create_timestamp => start_date..end_date).where(condition).order(create_timestamp: :desc).limit(MAX_FETCH_SIZE_CSV)
    else
      @transactions = PaymentTransactionFlat.where(:create_timestamp => start_date..end_date).where(condition).order(create_timestamp: :desc).limit(MAX_FETCH_SIZE + 1)
      if @transactions.present?
        @transactions = @transactions.to_a
        if @transactions.count > MAX_FETCH_SIZE
          @transactions = @transactions[0..(MAX_FETCH_SIZE - 1)]
          @transactions_exceed_limit = true
        end

=begin
        @transactions = @transactions.paginate(:per_page => params[:per_page], :page => @page, :total_entries => @transactions.count)
=end
      end
    end
  end

  def details
    @integratedApi=false
    if TRANSACTION_SEARCH_REST_API_ENABLED_FLAG == 'Y'
      @integratedApi=true
    @transaction = params[:id]
      else
    @transaction = PaymentTransactionFlat.transaction_details(params[:payment_transaction_id])
    if @transaction.present?
      @settlement = PaymentTransactionFlat.settlement_transaction(@transaction['payment_transaction_id']).first
      @response_cc_auth = PaymentTransactionFlat.response_cc_auth(@transaction['payment_transaction_id']).first
      if @settlement.present?
        @auth_transaction = PaymentTransactionFlat.authorization_transaction(@settlement['auth_pmt_transaction_id']).first
        @customer_billing_address = PaymentTransactionFlat.customer_billing_address(@settlement['auth_pmt_transaction_id']).first
        @settlement_history = PaymentTransactionFlat.settlement_transaction_history(@settlement['payment_transaction_id'])
      end
    end
    end

  end

  def retrieve_payload(account_number, tender_class)
    builder = Nokogiri::XML::Builder.new do |xml|
      xml.ProtectPanRequest('xmlns' => 'http://api.gsicommerce.com/schema/checkout/1.0') do
        xml.PaymentAccountNumber_ account_number
        xml.TenderClass tender_class
      end
    end

    return builder.to_xml
  end

  def retrieve_account_number(account_number)
    if account_number.present? && account_number =~ /^[0-9]+$/
      rest_client = RestClient::Resource.new(PAYMENTS_URI, PAYMENTS_USERNAME, PAYMENTS_PASSWORD)

      PaymentsHelper::TENDER_CLASS.each do |key, value|
        begin
          response = rest_client.post retrieve_payload(account_number, value), :content_type => 'application/xml'
          parsed_response = Hash.from_xml(response)
          account_number = parsed_response.try(:[], 'ProtectPanReply').try(:[], 'Token') || account_number
          break
        rescue RestClient::RequestFailed
          next
        end
      end
    end
    account_number
  end

  # Code for CSV generation

  # Enable the CSV library
  require 'csv'

  # Action for generating the CSV
  def csvexport
    respond_to do |format|
      format.csv do
        send_data export_to_csv(results),
                  filename: 'transactions.csv',
                  type: 'text/csv; charset=utf-8; header=present',
                  disposition: 'attachment'
      end
    end
  end

  # Method for generating the csv file
  def export_to_csv(records)
    # Header names used in CSV file
    csv_header = ['Transaction Id', 'Order Id', 'Store Id', 'Transaction Date', 'Transaction Type', 'Tender Type', 'Token', 'Amount', 'Currency', 'Response Code']
    CSV.generate do |csv|
      csv << csv_header
      records.each do |record| # Quick fix for CSV download problem to export only specified columns
        csv << [record['payment_transaction_id'], record['payment_session_id'], record['store_id'], record['create_timestamp'].in_time_zone(@timezone).strftime('%B %d, %Y - %l:%M %p'), record['transaction_type'],
                record['tender_type'], record['payment_acct_unique_id'],
                if record['transaction_amount'].to_s.present?
                  record['settlement_type'].to_s.casecmp("C")== 0 ? '-$' +
                record['transaction_amount'].to_s : '$' + record['transaction_amount'].to_s else ' ' end, record['iso_currency_code'],
                record['response_code'] == ('F') ? 'Payment Service Error' : record['response_code']]
      end
    end
  end

  def get_store_timezone
    render json: ActiveSupport::TimeZone.find_tzinfo(get_timezone(@selected_store)), status: :ok
  end

  private

  def set_store_and_timezone
    params[:store_ids] = get_default_store if params[:store_ids].blank?
    @selected_store = params[:store_ids]
    @store_for_service = replace_with_store_mappings(@selected_store, ApplicationHelper::PAYMENTS_SERVICE)
    @timezone = get_timezone @selected_store
    zone_map = JSON.parse((ActiveSupport::TimeZone.find_tzinfo @timezone).to_json)
    @moment_timezone = zone_map['identifier']
  end

  def tenders_and_transaction_types
    @tenders = Rails.cache.fetch(:payment_tenders) {PaymentRecord.tenders}
    @transaction_types = Rails.cache.fetch(:payment_transaction_types) {PaymentRecord.transaction_types}
  end

  def settlement_status
    @settlement_statuses = Rails.cache.fetch(:payment_settlement_statuses) {PaymentRecord.settlement_status}
  end
end

samedi 12 janvier 2019

how delete user and posts of user

i have two model User and post. user have has_many posts and post are based on user. I want When user is delete automatically The posts of that user should be delete how to do this i am very new to ruby..

class User < ApplicationRecord
    has_many :posts
end

class User < ApplicationRecord
    belongs_to :user
end

class UsersController < ApplicationController
    def destroy
    @user = User.find_by(id:params[:id])
    @user.posts
    @user.destroy
end

I am try the above code but only user are deleted His posts are not deleted Thanks Advance!

vendredi 11 janvier 2019

Folders in paperclip gem

I am using paperclip gem for file uploading. How I can create folders in my website using papeclip so that images can then be added to specific folder?

Net-SSH/Capistrano problem: "Could not parse PKey: no start line"

For years I've been deploying my Rails 3.2.13 app successfully using Capistrano. But just today I ran into the dreaded ArgumentError: Could not parse PKey: no start line when connecting to the server.

From other posts I gather this is actually an issue with the net-ssh gem, which Capistrano uses to make the connection. Apparently older versions of net-ssh aren't compatible with the key files created by more recent versions of OpenSSH. (See here and here for example.)

This diagnosis is confirmed by the following little irb session:

irb(main):006:0> require 'net/ssh'
=> false
irb(main):007:0> Net::SSH::KeyFactory.load_private_key('~/.ssh/id_rsa')
ArgumentError: Could not parse PKey: no start line

I guess I updated my private key file recently when I changed my password, and now it's incompatible with my version of net-ssh (v2.7.0).

I can't upgrade net-ssh since I'm stuck with Ruby 1.9.3.

Is there maybe a way to get back to an old/compatible version of the private key file? Or some other solution perhaps?

jeudi 10 janvier 2019

Updating and accessing a session with Ruby on Rails

Im working with ruby on rails 2.5.

I have an object "payment_plan". This object can change with a toggle behavior that changes, and I need to keep this object alive thorough all the session and at the end it should be save par of it in my mongo db. I need to access the latest status of the object always. The controller should be capable to update the object and the view should be able to access the latest state of the object.

Any insights on how to do something like this would be great :)

I have try to create a helper function in the application controller but had problem accessing it from the view.

Also I prefer not to save the state of the object in the db, because it will be too many db calls later.

Thanks in advance!!

[railstutorial.org]: Michael Hartl book's Contain is not visible

Book's chapter is not loading.

a console is showing the following error:

Failed to load resource: net::ERR_NAME_NOT_RESOLVED

You can check out from the following link:

https://www.railstutorial.org/book/static_pages

change border-color on select value in dropdown

how to change the border-color on value select using jquery.

<div class="col-md-4 col-sm-12 col-xs-12">
  <div class="form-group">
    <span class="input input--ichiro" style="float: left">
      <%= startup.collection_select :stage_id, Stage.where('id <> 1'), :id, :name, {}, {class: "form-control input__field input__field--ichiro", id: "stage_id" } %>
      <label class="input__label input__label--ichiro" for="stage_id">
         <span class="input__label-content input__label-content--ichiro">What stage is your startup in? *</span>
       </label>
    </span>
  </div>
</div>

.css file

.input__label.input__label--ichiro::before{ border-bottom: 2px solid #e74c3c !important; }

jquery

$(".collection_select .input__label.input__label--ichiro ").on('blur',function(){ 
 if ( $('option:selected', this).val() == 0 ){
   $(this).css('border-color', '#C80000');     
  }
 else if ($(this).val() > 0) {
   $(this).css('border-color', '#BDC7BC');    
 }

});

this jquery is not working. can anybody help me out?

lundi 7 janvier 2019

Split string by multiple consecutive delimiters on ruby.

I want to split a string by whitespaces, , and . using ruby commands. word.split(" ") will split by white spaces; word.split(",") will split by ,; word.split(".") will split by . How to do all three at once?

puts "Enter string "
text=gets.chomp
frequencies=Hash.new(0)
delimiters = [',', ' ', "."]
words = text.split(Regexp.union(delimiters))
words.each { |word| frequencies[word] +=1}
frequencies=frequencies.sort_by {|a,b| b}
frequencies.reverse!
frequencies.each { |wor,freq| puts "#{wor} #{freq}"}


Current (wrong) Output
Enter string 
hello this is a hello, allright this is a hello.

hello 3
a 2
is 2
this 2
allright 1
 1


I donot want the last line of the output. It considers the space as a 
word too. This may be because there were consecutive delimiters (, & " 
") . How to solve this issue

Expected Output

Enter string 
hello this is a hello, allright this is a hello.


hello 3
a 2
is 2
this 2
allright 1

undefined method `unserialize_attribute' in ruby on rails

I am working on upgrading rails application, I have a method unserialize_attribue in rails 3 but I am not able to see this method in rails 5.

What is the alternative for unserialize_attribute in rails 5 or any suggestion on what can I do, Thanks

dimanche 6 janvier 2019

How do I render a partial within an iterator in a view? | ruby on rails

I'm trying to display a form from another controller in a view within an iterator.

Every time I try to run the code it gives me an error: 'NoMethodError at / undefined method `model_name' for nil:NilClass'

I've tried rendering the partial from another controller and I've also tried rendering a partial within the same controller but both return an error. This is might be because it's within iterator for another collection?

<% @services.each do |service| %>

  <div class='service-info'>
    <%= service.name %>
    <%= service.description %>
  </div>

  <%= simple_form_for(@visit) do |f| %>
    <%= f.error_notification %>
    <%= f.error_notification message: 
    f.object.errors[:base].to_sentence 
    if f.object.errors[:base].present? %>

    <%= f.input :service %>
    <%= f.input :visit_date %>
    <%= f.input :note %>

    <%= f.button :submit %>
  <% end %>

<% end %>

I would like the 'visit' form to appear below each 'service' in the view.

vendredi 4 janvier 2019

Rails: elsif && conditional statement in controller action not working

I am working on a multistep form, which is based on Ryan Bates' #217 Multistep Forms tutorial. I needed to implement conditional navigation inside the form and things became quite complex.

Navigation inside the form is working but I have problems with the conditions in my controller relative to the commit.

def create
  @order.current_step = session[:order_step]
  if @order.valid?
    if params[:back_button]
      @order.previous_step
    elsif params[:back_button_wiretransfer] && @order.payment = 'Wiretransfer'
      @order.payment_options_step
    elsif params[:back_button_credit_card] && @order.payment = 'Credit card'
      @order.creditcard_options_step
    elsif @order.thirdlast_step? && params[:commit] == 'Wiretransfer'
      @order.payment = nil
      @order.payment = 'Wiretransfer'
      @order.confirmation_step
    elsif @order.thirdlast_step? && params[:commit] == 'Credit card'
      @order.next_step
    elsif @order.secondlast_step?
      @order.payment = nil
      @order.payment = 'Credit card'
      @order.next_step
    elsif @order.last_step? && @order.payment = 'Wiretransfer'
      ...
    elsif @order.last_step? && @order.payment = 'Credit card'
      ...
    else
      @order.next_step
    end
    session[:order_step] = @order.current_step
  end
  if @order.new_record?
    render "new"
  else
    ...
  end
end

Currently the controller is not able to apply the last two elsif conditions with @order.payment = 'wiretransfer' or @order.payment = 'credit card'.

All other conditions are working, but when I checkout through the credit card section the wiretransfer part is executed.

When I use:

elsif @order.last_step? && @order.payment == 'Wiretransfer'
  ...
elsif @order.last_step? && @order.payment = 'Credit card'
  ...

'Credit card' works, but 'wiretransfer' does not. Since I display the payment attribute on the last step of the form I know it persists at that step although it wasn't saved yet to the database.

What am I doing wrong? I found out that sometimes I have to use = and other times ==, but the rational is not clear to me.

In the view I have to use == (comparison) such as in:

<% elsif @order.last_step? && @order.payment == "Credit card" %>

to trigger the right divs.

In the controller the two conditions

elsif @order.thirdlast_step? && params[:commit] == 'Wiretransfer' 
elsif @order.thirdlast_step? && params[:commit] == 'Credit card'

work only with ==, while all the others only with =. I started by using only == in the controller, but when I do so nothing gets executed and new is rendered.

Thank you in advance!

DeprecationWarning: 'root' is deprecated, use 'global'

I am working on project and stuck at a point where i got this error unexpected token at '(node:14500) [DEP0016] DeprecationWarning: 'root' is deprecated, use 'global' because I have use JavaScript tag at the end of the view file. Moreover if I use application JavaScript file instead of admin/admin then it works fine but i need to use admin layout script file. enter image description here

So how can i fix this issue??

jeudi 3 janvier 2019

This SO post explains how to include JavaScript specific to a page.

However, this method is causing this error in charges.js at line 1: Uncaught SyntaxError: Unexpected token <

In the Chrome console, the doctype declaration is highlighted as having the error.

The simplified view is below. The JavaScript file in question is empty.

Why is this happening?

<% content_for :javascript_includes do %>
  <%= javascript_include_tag "charges.js" %>
<% end %>

<style>
    #pageBox {
        width: 600px;
        margin: 60px auto;
    }

    .header {
        text-align: center
    }

    .content {
        margin-top: 50px;
    }
</style>

</div>

Rails-redis: How to forece key to expire and get recalculated

In our app we have some administartive webpages which show lots of accumulated statistics, for user interaction, sales, products overviews and etc. . Some content isvery heavy to compute and is outsourced to some partials. These in turn are then cached in redis. I can view the partial per access to the corresponding key:

ap redis.keys "views/admin*"
# => "views/partial/sales",
# => "views/partial/customer",
# => "views/partial/customer_exp",

my simple question, which i am unable to solve, is the folling: How can i update one of those partials. Is it possible to reload a single key from redis? Somehow the app should push an updated version of for example views/partial/sales to redis but how can i trgger this re-rendering/computing?

Specify parameter name for additional resource actions

I have some nested resources specified in routes.rb

resources :installation, except: %i[index edit update show] do
     resources :configuration, shallow: true, except: %i[index show] 
end

which generate the folling routes:

installation_configuration_index POST   /installation/:installation_id/configuration(.:format)     configuration#create
  new_installation_configuration GET    /installation/:installation_id/configuration/new(.:format) configuration#new
              edit_configuration GET    /configuration/:id/edit(.:format)                          configuration#edit
                   configuration PATCH  /configuration/:id(.:format)                               configuration#update
                                 PUT    /configuration/:id(.:format)                               configuration#update
                                 DELETE /configuration/:id(.:format)                               configuration#destroy
              installation_index POST   /installation(.:format)                                    installation#create
                new_installation GET    /installation/new(.:format)                                installation#new
                    installation DELETE /installation/:id(.:format)                                installation#destroy

I would now like to add some additional actions to the configuration, such as enable,disable

resources :installation, except: %i[index edit update show] do
  resources :configuration, shallow: true, except: %i[index show] do
    post :enable
    post :disable
  end
end

whichs adds some the following:

 configuration_enable POST   /configuration/:configuration_id/enable(.:format)          configuration#enable
 configuration_disable POST   /configuration/:configuration_id/disable(.:format)         configuration#disable

This is fine, except for the fact that these new actions use the parameter :configuration_id instead of :id. This makes it a bit annoying to use before_actions that check for parameter validity across the whole controller.

I would like to end up something similar to the following:

 configuration_enable POST   /configuration/:id/enable(.:format)          configuration#enable
 configuration_disable POST   /configuration/:id/disable(.:format)         configuration#disable

I have already searched and found things like using param: :id or key: id, none of which had the desired effect. What works but is a bit messy is adding the new routes seperately like so:

post 'configuration/:id/enable', action: 'enable', as: 'configuration/enable', to: 'configuration#enable'
post 'configuration/:id/disable', action: 'disable', as: 'configuration/disable', to: 'configuration#disable'
resources :installation, except: %i[index edit update show] do
  resources :configuration, shallow: true, except: %i[index show]
end

I there a cleaner way to accomplish the same thing while still using nested resources?

How to Set Routes in Ruby onRails?

I new to ruby on rails and getting confused in naming routes.

Can some tell me the do's and don't approach that needs to be followed while naming the routes and any other tips with examples.

mercredi 2 janvier 2019

Angular 6: All parameter is passed but api is not call ( data is comming from rails api)

In drop down when i select one opetion and all parameter is passed, but api is not called and previous data shown as it is. also error is not showing.

Is it possible to use slim template engine without rails or sinatra?

I plan to make html markup using slim template engine. However is it possible to compile it without backend (e.g.: rails, sinatra)? Like just compile .slim file in to a plain html? Or rails/sinatra is required?

mardi 1 janvier 2019

Ruby on Rails: stripping file extension from image request and redirecting to 404

An image is located in the Rails directory at public/images/subDir/X.png.

In the development environment, this loads perfectly.

In production, Rails strips off the file extension (.png) and redirects requests to public/images/subDir/X instead, which results in a 404.

How do you get Rails to not redirect image requests like this?

We're using RoR 3.2.x.