mardi 31 décembre 2019

why select helper does not auto show the selected value?

This code works:

select("questionnaire", "is_active", options_for_select([["no", false], ["yes", true]], @questionnaire.is_active) )

But this will not:

select("questionnaire", "is_active", options_for_select([["no", false], ["yes", true]]) )

Why doesn't rails know to handle the selected value by itself? What's the logic?

lundi 30 décembre 2019

previous_changes does not list the hash changes in ruby

I have a hash column in my table when I change the value of particular hash the changes doesn't list in previous_changes. Can anyone help with this..

But the value gets updated in the table. It happens only for the hash attributes, others works fine. For an example, settings table.

additional_settings column which is of type hash. When I tried changing a key-value pair, e.g.

settings.additional_settings[:key] = "some_value"

The changes does not listed in self.previous_changes

Here is the code in settings.rb,

if self.previous_changes.present? =>(true because of changes in "updated_at" attribute)
  model_changes = self.previous_changes  => (here the change made in hash is not listed)
end

Unable to render different form for same Projectsite

I have a project_site model that saves project attributes. I have created a manager_remark model that has a form for each project_site created. Now I have created a model director and I want to render a different form I have created a director model that has an attribute :remark and : status but i am getting error. is it possible to have a different form for the same project_site.

routes.rb

  resources :project_sites do
    resources :manager_remarks
    resources :director_remarks

  end

project_site_controller.rb

  def index
    @project_sites = current_user.project_sites.order("created_at DESC").paginate(page: params[:page], per_page: 10)
  end

  def show
    @manager_remark = ManagerRemark.new
    @manager_remark.project_site_id = @project_site.id
    @director_remarks = DirectorRemark.new
    @director_remarks.project_site_id = @project_site.id

  end

director_remarks_controller.rb

  def create
    @director_remarks = DirectorRemark.new(remark_params)
    @director_remarks.project_site_id = params[:project_site_id]
    @director_remarks.save

    redirect_to project_site_path(@director_remarks.project_site)
  end

  def remark_params
    params.require(:manager_remark).permit(:remark, :status)
  end

director_remark_form.html.erb

<%= form_for [ @project_site, @director_remarks ] do |f| %>
  <div class="row">
    <div class="medium-6 columns">
      <%= f.radio_button :status, true  %>
      <%= f.label :approve %>
      <%= f.radio_button :status, false  %>
      <%= f.label :reject %>
    </div>
    <br>
    <br>
    <div class="medium-6 cloumns">
      <%= f.label :remark %><br/>
      <%= f.text_area :remark %>
    </div>

      </div>
    <div>
      <%= f.submit 'Submit', :class => 'button primary' %>
    </div>

<% end %>

I can render a form for user role manager but I am unable to render a form for user role director for the same project site. Please help.

expose array of objects elements inside the parent object in RAILS

I want to expose subBranches inside array of objects to the parent object as mentioned in Convert To section.

The actual array of objects is :

Original Data :

[
  {
    "ServiceTypeID": 3,
    "ChildCount": 0,
    "IsSelect": 0,
    "subBranches": [
      {
        "ServiceTypeID": 13,
        "ChildCount": 0,
        "IsSelect": 0
      },
      {
        "ServiceTypeID": 14,
        "ChildCount": 0,
        "IsSelect": 0
      },
      {
        "ServiceTypeID": 15,
        "ChildCount": 0,
        "IsSelect": 0
      }
    ]
  },

]

Convert to (basically expose subBranches to parent object):

This is the expected response :

[
  {
    "ServiceTypeID": 3,
    "ChildCount": 0,
    "IsSelect": 0,
    "subBranches":'',
    "ServiceTypeID": 13,
    "ChildCount": 0,       
    "IsSelect": 0,
    "ServiceTypeID": 14,
    "ChildCount": 0,
    "IsSelect": 0,
    "ServiceTypeID": 15,
    "ChildCount": 0,
    "IsSelect": 0
  }
]

How do I get This JSON?

how to add different CSS style class internary operator output in ROR

hi i want to add different CSS style on these two output how can i do that in ruby on rails?

<%= manager_remark.decision ? 'Approved' : 'Rejected' %>

samedi 28 décembre 2019

unable to print the status if neither true nor false in rails

Hi i have i model name ProjectSite and a model name ManagerReamark which takes a decision boolean value. ProjectSite has many ManageRemark. default value of decision is nil. how can i print status as pending when there is no ManagerRemark? here is code

                <% project_site.manager_remarks.each do |manager_remark| %>
              <% if manager_remark.decision == false %>
                <td><%= 'Rejected' %></td>
              <% elsif manager_remark.decision == true %>
                <td><%= "Approved" %></td>
              <% else %>
                <td><%= "Pending" %></td>
              <% end %>
           <% end %>

jeudi 26 décembre 2019

How Do I make Checkboxes retain their value after submitting the form in Rails

This Is the form

<%= form_tag method: "post" do |f| %>
 <script src="https://cdn.iris.nitk.ac.in/design_system/assets/js/vendors/form-components/toggle-switch.js"></script>

<table class="table table-striped">
<thead>
<tr>
  <th></th>
  <th>Title</th>
  <th>Pin To Modules Tab?</th>


</tr>
</thead>

<tbody>
<tr>
  <td class="image"> <%= image_tag("https://cdn.iris.nitk.ac.in/images/new_dashboard/button_Human.png", class: 'list_image') %></td>
  <td>Profile</td>
  <td><%= check_box_tag '1', true, true, :checked => true, data: {toggle: "toggle", on: "Yes", off: "No", onstyle: "success", offstyle: "danger"} %></td>
</tr>
<tr>
  <td class="image"> <%= image_tag("https://cdn.iris.nitk.ac.in/images/new_dashboard/withdraw.png", class: 'list_image') %></td>
  <td>Withdraw Admission</td>
  <td><%= check_box_tag '2', true, true, :checked => true, data: {toggle: "toggle", on: "Yes", off: "No", onstyle: "success", offstyle: "danger"} %></td>
</tr>
<tr>
  <td class="image"> <%= image_tag("https://cdn.iris.nitk.ac.in/images/new_dashboard/attendance.png", class: 'list_image') %></td>
  <td>Feedback Forms</td>
  <td><%= check_box_tag '4', true, true, :checked => true, data: {toggle: "toggle", on: "Yes", off: "No", onstyle: "success", offstyle: "danger"} %></td>
</tr>
<tr>
  <% if can? :my_grade_card, Student %>
  <td class="image"> <%= image_tag("https://cdn.iris.nitk.ac.in/images/new_dashboard/button_manage_users.png", class: 'list_image') %></td>
  <td>My Grade Card</td>
  <td><%= check_box_tag '5', true, true, :checked => true, data: {toggle: "toggle", on: "Yes", off: "No", onstyle: "success", offstyle: "danger"} %></td>
  <% end %>
</tr>
</tbody>
</table>


<%= submit_tag "Pin Modules",:class => "btn btn-primary btn-lg btn-block" %>

This is how i'm saving in my db

def pin_modules

if request.post?
  present_user = User.find(current_user.id)
  present_user.misc_data[:pin_modules]=[]
    (1..17).each do |i|
      (params[i.to_s] ? (present_user.misc_data[:pin_modules] ||= []) << i : next)
    end
  present_user.save!
  redirect_to '/'
end

end

if the value is true then its saved in my db. and for some reason as i have seen the form params values which are only true are passed. i want my form to retain its value either if its true or false for a particular user. can someone help me with this?

not able to print date in Month_name-yyyy format in rails

hi i am taking date input in mm-yyyy format i want to print date in formate of month_name-yyyy format. i have used strftime but i am not to able print the date as my required format. index.html.erb code

          <td><%= project_site.name.titleize %></td>
          <td><%= project_site.created_at.strftime('%b-%Y') %></td>
          <td><%= link_to ' View attendance', project_site.file, :class => "fi-page-export-csv" %></td>
          <% project_site.manager_remarks.each do |manager_remark| %>
            <% if manager_remark.decision == false %>
              <td><%= 'Rejected' %></td>
            <% elsif manager_remark.decision == true %>
              <td><%= "Approved" %></td>
            <% else %>
              <td><%= "Pending" %>
            <% end %>
         <% end %>
         <td><%= project_site.attendance_month.strftime('%b %Y') %></td>
          <td><%= link_to 'Remark ', project_site %><span>(<%= project_site.manager_remarks.size %>)</span></td>
          <td><%= link_to 'Edit', edit_project_site_path(project_site) %></td>
          <td><%= link_to 'Delete', project_site, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        </tr>

form.html.erb code

        <%= form.label :name %>
        <%= form.text_field :name %>
      </div>
  <!--
      <div class="field medium-3 columns">
        <%= form.label :date %>
        <%= form.text_field :date, class: 'datepicker' %>
      </div>
  -->
        <div class="field medium-3 columns">
          <%= form.label :upload_attendance %>
          <%= form.file_field :file, :class=> 'attendance-file' %>
        </div>

        <div class="field medium-6 columns">
          <%= form.label :attendance_month %>
          <%= form.date_select :attendance_month, { :discard_day => true, :discard_month => false, :discard_year => false },:class => 'datetime' %>
        </div>

how can i get mm/yy output while use of 'form.date_select :date' in rails

i want to acess date in mm/yyyy format on show page but it gives output as {1=>2019, 2=>2, 3=>1}. how can i make output as {1=>2019, 2=>2, 3=>1} to mm/yy format in user view page.

form.html.erb

          <div clas="field medium-6 columns">
        <%= form.label :attendance_month %>
        <%= form.date_select :date, { :discard_day => true, :discard_month => false, :discard_year => false } %>
      </div>

show.html.erb

<%= project_site.date %>

mercredi 25 décembre 2019

Run my app ruby on local bash ubuntu on windows

I have this answer after try to run my app in ruby on mi bash ubuntu on windows 10

Bundler could not find compatible versions for gem "bundler": In Gemfile: rails (= 4.1.0) was resolved to 4.1.0, which depends on bundler (< 2.0, >= 1.3.0)

Current Bundler version: bundler (2.1.2) This Gemfile requires a different version of Bundler. Perhaps you need to update Bundler by running gem install bundler?

Could not find gem 'bundler (< 2.0, >= 1.3.0)', which is required by gem 'rails (= 4.1.0)', in any of the sources.

Bundler could not find compatible versions for gem "coffee-rails": In Gemfile: coffee-rails (~> 4.0.0)

social-share-button (~> 0.1.6) was resolved to 0.1.10, which depends on
  coffee-rails

¿What do you recommend me?

dimanche 22 décembre 2019

Bundler installation dos't respond

My disto is Centos 7. I install ruby with :

yum install ruby.

So i have :

[root@localhost ~]# ruby -v
ruby 2.0.0p648 (2015-12-16) [x86_64-linux]

and :

[root@localhost ~]# gem -v
2.0.14.1

Now when i use bundle install command it return :

-bash: bundle: command not found

I try to install bundler with :

gem install bundler

It wait and wait and do not respond any thing.

My goal is running bundle install command without error.

What should i do?

jeudi 19 décembre 2019

Why ngrok send me a 403 Forbidden

I try to work with a webhook to get a JSON, I read that I should install ngrok because webhooks do not work locally, so I installed ngrok, and tried to follow this small tuto : https://medium.com/@derek_dyer/rails-webhooks-local-development-7b7c755d85e3

I created my routes :

get 'invoice/webhooks'
post 'invoice/webhooks' =>'invoice#webhooks'

And my controller :

def webhooks
   render json: response.body, status: 200
end

I also plugged my URL : https://ce0d99f7.ngrok.io/invoice/webhooks in my service to receive the webhook

I run ./ngrok http 3000 in my terminal and I receive a message

POST /invoice/webhooks         403 Forbidden

Is anyone knows how to fix that ?

mardi 17 décembre 2019

Generating new version of all.js to reflect changes from application.js: how does Rails 3.2.12 compile all.js?

There are similar posts like this and this, but none answer the question.

How does all.js get compiled in production for Rails 3.2.12? As illustrated below by the production.rb file, compiling assets is disabled so it's unclear how all.js gets generated in the first place.

The root issue is how to update all.js to reflect the newest code in application.js. Restarting the server hasn't helped, so what triggers all.js to get recompiled?

Test::Application.configure do
# Settings specified here will take precedence over those in config/application.rb

# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
    config.cache_classes = true

    # Full error reports are disabled and caching is turned on
    config.consider_all_requests_local       = false
    config.action_controller.perform_caching = true

    # Specifies the header that your server uses for sending files
    config.action_dispatch.x_sendfile_header = "X-Sendfile"

    # For nginx:
    # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'

    # If you have no front-end server that supports something like X-Sendfile,
    # just comment this out and Rails will serve the files

    # See everything in the log (default is :info)
    # config.log_level = :debug

    # Use a different logger for distributed setups
    # config.logger = SyslogLogger.new

    # Use a different cache store in production
    # config.cache_store = :mem_cache_store

    # Disable Rails's static asset server
    # In production, Apache or nginx will already do this
    config.serve_static_assets = false

    # Enable serving of images, stylesheets, and javascripts from an asset server
    # config.action_controller.asset_host = "http://assets.example.com"

    # Disable delivery errors, bad email addresses will be ignored
    # config.action_mailer.raise_delivery_errors = false

    # Enable threaded mode
    # config.threadsafe!

    # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
    # the I18n.default_locale when a translation can not be found)
    config.i18n.fallbacks = true

    # Send deprecation notices to registered listeners
    config.active_support.deprecation = :notify

    # Compress JavaScripts and CSS
    config.assets.compress = true

    # Don't fallback to assets pipeline if a precompiled asset is missed
    config.assets.compile = false

    # Generate digests for assets URLs
    config.assets.digest = true

    # Defaults to Rails.root.join("public/assets")
    # config.assets.manifest = YOUR_PATH

    # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
    # config.assets.precompile += %w( search.js )

    # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
    # config.force_ssl = true   
end

Unable to connect when LDAP Channel Binding is enabled

Trying to connect to AD by enforcing the LDAP Channel Binding https://portal.msrc.microsoft.com/en-us/security-guidance/advisory/ADV190023

Ending up with the below error

=> #<Net::LDAP::PDU:0x0000000013568ea8
  @app_tag=1,
  @ldap_controls=[],
  @ldap_result=
      {:resultCode=>49,
       :matchedDN=>"",
       :errorMessage=>"80090346: LdapErr: DSID-0C09056D, comment: AcceptSecurityContext error, data 80090346, v2580\u0000"},
  @message_id=1>

Does anyone know is there a way how to connect by enabling the channel binding?

lundi 16 décembre 2019

MimeMagic::Encoding error when recreating versions in carrierwave

I am having difficulties recreating versions in carrierwave. The initial upload goes well only the recreate versions throws an error.

I have

mount_uploader :file_name, DiapoUploader

def reprocess
  begin
    self.file_name.cache_stored_file!
    self.file_name.retrieve_from_cache!(self.file_name.cache_name)
    self.file_name.recreate_versions!
    self.save!
  rescue => e
    STDERR.puts  "ERROR: Diapo: #{id} -> #{e.to_s}"
  end
end

in my model Diapo.rb and when I call

Diapo.all.each do |diapo|
  diapo.reprocess
end

in a rake task I get the following error:

$ rake carrierwave:reprocess_diapo          
ERROR: Diapo: 1 -> uninitialized constant MimeMagic::Encoding

$ rake carrierwave:reprocess_diapo --trace
** Invoke carrierwave:reprocess_diapo (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute carrierwave:reprocess_diapo
rake aborted!
NameError: uninitialized constant MimeMagic::Encoding
/Users/myaccount/.rvm/gems/ruby-stuff/gems/mimemagic-0.3.3/lib/mimemagic.rb:116:in `magic_match'
/Users/myaccount/.rvm/gems/ruby-stuff/gems/mimemagic-0.3.3/lib/mimemagic.rb:81:in `by_magic'
/Users/myaccount/.rvm/gems/ruby-stuff/gems/carrierwave-0.11.1/lib/carrierwave/sanitized_file.rb:318:in `mime_magic_content_type'
/Users/myaccount/.rvm/gems/ruby-stuff/gems/carrierwave-0.11.1/lib/carrierwave/sanitized_file.rb:250:in `content_type'
/Users/myaccount/.rvm/gems/ruby-stuff/gems/carrierwave-0.11.1/lib/carrierwave/uploader/cache.rb:96:in `sanitized_file'
/Users/myaccount/.rvm/gems/ruby-stuff/gems/carrierwave-0.11.1/lib/carrierwave/uploader/cache.rb:128:in `cache!'
/Users/myaccount/.rvm/gems/ruby-stuff/gems/carrierwave-0.11.1/lib/carrierwave/uploader/versions.rb:226:in `recreate_versions!'
/Users/myaccount/Development/REPRO/projecty/lib/tasks/carrierwave.rake:11
/Users/myaccount/Development/REPRO/project/lib/tasks/carrierwave.rake:9:in `each'
/Users/myaccount/Development/REPRO/project/lib/tasks/carrierwave.rake:9
.
.
.
Tasks: TOP => carrierwave:reprocess_diapo

What am I missing?

How to reprocess image versions in carrierwave?

I am trying to write a rake task which should reprocess all my uploaded image versions after I change the version parameters in the uploader file.

I would like to be able to call it from bash or the rails console. For that reason I wrote a rake task and a method reprocess for the relative model diapo.rb which I can call in the rake task. (I followed this answer https://stackoverflow.com/a/31220535)

Currently I have a resource model Diapo.rb

class Diapo < ActiveRecord::Base

  mount_uploader :file_name, DiapoUploader

  def reprocess
    begin
      self.cache_stored_file!
      self.retrieve_from_cache!(self.cache_name)
      self.recreate_versions!
      self.save!
    rescue => e
      STDERR.puts  "ERROR: MyModel: #{id} -> #{e.to_s}"
    end
  end
end

In my uploader file I have specified a series of versions diapo_uploader.rb

class DiapoUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick
  include CarrierWave::MimeTypes

  process :set_content_type

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.downcase.pluralize}/#{mounted_as}/#{model.id}"
  end

  version :diapo0500, :if => :diapo? do
    process :resize_to_fit => [500, 500]
    process :quality => 50
  end

  version :thumb, :if => :diapo? do
    process :resize_to_fit => [200, 200]
    process :quality => 50
  end
end

I wrote a rake task: carrierwave.rake

# CarrierWave rake tasks
#
# Task:   reprocess
# Desc:   Reprocess all diapos
# Usage:  rake carrierwave:reprocess_diapo

namespace :carrierwave do
  task :reprocess_diapo => :environment do
    Diapo.all.each do |d|
      d.reprocess
    end
  end
end

currently I get:

$ rake carrierwave:reprocess_diapo
ERROR: MyModel: 1 -> undefined method `cache_stored_file!' for #<Diapo:0x111cd8428>
ERROR: MyModel: 2 -> undefined method `cache_stored_file!' for #<Diapo:0x111c98300>
ERROR: MyModel: 3 -> undefined method `cache_stored_file!' for #<Diapo:0x111c97db0>
ERROR: MyModel: 4 -> undefined method `cache_stored_file!' for #<Diapo:0x111c97798>
ERROR: MyModel: 5 -> undefined method `cache_stored_file!' for #<Diapo:0x111c97108>
ERROR: MyModel: 6 -> undefined method `cache_stored_file!' for #<Diapo:0x111c96af0>

Rails is 3.2.5 Carrierwave is 0.11.1

What am I doing wrong?

Thank you in advance !

How to check if I have some error in my hash

I try to check if I have an error in my token, In my view it works like this and it seems to be Ok :

<% if @token['error'].present?%>
    <%= @token['error']%> // display the message of the error
    <%= flash[:error]%> //display ERROR
    <% else %>
    <%= @token%> // display the token
    <p>Ok</p>
<%end%>

But in my controller, I can't do that :

 if @token['error'].present?
            flash[:error] = "ERROR"
        else
            @token = HTTParty.post('https://mooncard23-sandbox.biapi.pro/2.0/auth/token/access', 
                body: {
                    client_id: XXXXXXXXXX,
                    client_secret: "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
                    code: @decoded_code
                }
            ) 
 end  

I have the error "undefined method `[]' for nil:NilClass". Do you know how to check if my token return an error ?

vendredi 13 décembre 2019

How to invoke custom method in GraphQL::Schema

I am trying to add a check in GraphQL::Schema. I want to call a method where I have defined my schema. One Way is to call the method in GraphqlController. But, I am not able to get the arguments that are sent in the mutation/query only the query string. For example, I want custom validation across all mutations and queries.

class MySchema < GraphQL::Schema
  #my method to be called for each query/mutation
  mutation(Types::MutationType)
  query(Types::QueryType)
end

jeudi 12 décembre 2019

how respond_to? method works in rails

I came across code snippet something like this.

attr_accessor :category, :search

  def run
    if respond_to?((category&.downcase).to_s, true)
      send(category.downcase)
    else
      send(:tag)
    end
  end

But I am not sure what does belongs_to? does in this scenerio. Any help would be greatly appreciated. Thanks !

ActiveRecord SQLSever Adapter support for SQL Server 2019

Does tinytds -v 0.7.0 running on ruby 1.9.3 support sql server -v 2019 ? 0.7.0v worked for me till sql server -v2016 but not beyond that and I'm getting NotImplementedError My activerecord-sqlserver-adapter version is 3.2.6 and rails version 3.2

enter image description here

mercredi 11 décembre 2019

Rails: Delay in after commit callback

I'm new to Ruby on Rails. I have defined a method and set it as after commit callback of a model. However the view template ( for any action like create) from the corresponding controller is getting rendered before the callback is invoked. I need it to be the other way round.

lundi 9 décembre 2019

No route matches [GET] “/admin/orders/197/update” if i change method like put or patch it still gives same error with the method name i put there

orders.rb

if order.payment_status == 'Paid' && order.received_by_admin != 'true'
        link_to "Payment Not Recieved", "orders/#{order.id}/update?payment_status=paid" , class: "member_link"

and this is in update function

if params[:payment_status].present?
  order.update!(received_by_admin: true)
end

this is in route file

resources :orders
  devise_for :admin_users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  mount_devise_token_auth_for 'User', at: 'auth'

ruby code, what is the code error below as shown?

Error message I get: undefined local variable or method `rev' for #

What is wrong with my if/else statement for the numbers method? Thank you for your help

This is my code:

def alphabetize(arr, rev=false)
  if rev
  arr.sort!{|item1, item2| item2<=>item1}
  else
  arr.sort!{|item1, item2| item1<=>item2}
  end
end

puts Array

numbers=[10, 12, 35, 17]
numbers.sort!
  if rev==true
    numbers.reverse! {|item1, item2, item3, item4|}
  else
    rev==false
    puts numbers
end

dimanche 8 décembre 2019

How to stub any post call in rest client in minitest rails

I am trying to find a way to stub any post call from restclient but I didn't found any solution to this. What I tried is

RestClient.stub(:post).returns(response)

But I getting error like wrong number of arguments.

Can anyone help

jeudi 5 décembre 2019

c/jruby-9.1.17.0/bin/bundle: jruby: bad interpreter: No such file or directory

I follow some of the online tutorial and install jruby. But turns out, i don't need that so i uninstall it . But when i bundle install
sh.exe": /c/jruby-9.1.17.0/bin/bundle: jruby: bad interpreter: No such file or directory this error is shown. I must admit that i am new to Ruby on rails. i spend several hours to find a solution on google but still stuck in it. I hope you guy can help me !

sh.exe": /c/jruby-9.1.17.0/bin/bundle: jruby: bad interpreter: No such file or directory

"How to use query parameter like strong parameter"?

How can i use query parameter as a strong parameter. This is my POST /tag method called by frontend to search posts.

def tag
  if params[:category] == 'Shop'
     render json: ShopPostPopulator.new(params[:search]).run
  else
     render json: Part.search(params[:search])
  end
end

If i want to use strong parameter instead of 'params[:search]', how should I do it.

mercredi 4 décembre 2019

Accessing Module inside a Thread Ruby

I have a Service which calls a method that runs inside thread. But the code inside thread has access to other module methods. The thread is getting struck when the module method is called.

Service:

  def place_order
    threads = []
    @responses = []
    order_params.each_with_index do |order, index|
      threads << Thread.new do
        @responses << Module1::Class1.place_order(order)
      end
   end
   threads.each &:join
  @responses
end

Module1::Class1's place_order method:

def place_order(options)
  order_params = { body: order_config(options).to_json }
  resp = make_request(:post, "/v3/order/", order_params).parsed_response
  Rails.logger.info "QWIK_CILVER::ORDERResponse:: #{resp.inspect}"
  ***The below code calls a method in different module which is not running******     
  Module2::SubModule1::Class1.parse(resp, self)
end

THe server is hanged and I am not even able to stop the server after that. Have to kill the process manually and start the server again. How can I call the Module2::SubModule1::Class1's method inside thread?

mardi 3 décembre 2019

"comparison of BigDecimal with nil failed"

I have problem posting banner using postman. It says something like "comparison of BigDecimal with nil failed". Here is my relations/banner.rb. Can anyone help me out.

module Relations
  module Banner
    extend ActiveSupport::Concern

    included do
      has_many :photos, as: :imageable, dependent: :destroy
      belongs_to :banner_price
      belongs_to :user
      belongs_to :post, inverse_of: :banners, optional: true

And my validation/banner.rb

module Validations
  module Banner
    extend ActiveSupport::Concern

    included do
      validates_presence_of(
        :user,
        :photos
      )

      validates(
        :price,
        price: true
      )

And this is my schema file:

  create_table "banner_prices", force: :cascade do |t|
    t.integer "size"
    t.integer "tier"
    t.decimal "price"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "banners", force: :cascade do |t|
    t.bigint "post_id"
    t.bigint "banner_price_id"
    t.integer "occurance", default: 0
    t.decimal "price"
    t.integer "occurance_limit", default: 0
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "user_id"
    t.string "web_link"
    t.string "title"
    t.index ["banner_price_id"], name: "index_banners_on_banner_price_id"
    t.index ["post_id"], name: "index_banners_on_post_id"
  end