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

samedi 30 novembre 2019

undefined local variable or method `article_params' for

articles_controller.rb

''' class ArticlesController < ApplicationController def index @articles = Article.all end

def show
  @article = Article.find(params[:id])
end

def new
end

def create
  @article = Article.new(article_params)

  if @article.save
    redirect_to @article
  else
    render new
end

private
  def article_params
    params.require(:article).permit(:title, :text)
  end
end

end

'''

routes.rb

'''

Rails.application.routes.draw do
  #layout=false 
  get 'welcome/index'
  get 'welcome/second'
  get 'articles/new'
  post 'articles/new'
  #get 'articles/show'
  #get 'articles/index'
  #get 'articles/new'
  resources :articles
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root 'welcome#index'
end'

'''

show.html.erb

'''

Rails.application.routes.draw do
  #layout=false 
  get 'welcome/index'
  get 'welcome/second'
  get 'articles/new'
  post 'articles/new'
  #get 'articles/show'
  #get 'articles/index'
  #get 'articles/new'
  resources :articles
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
  root 'welcome#index'
end

'''

index.html.erb '''

<h1>Listing articles</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
    <th></th>
  </tr>

  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= link_to 'Show', article_path(article) %></td>
    </tr>
  <% end %>
</table>

'''

new.html.erb

'''

<%= form_for :article, url: articles_path do |form| %>
 <h1>new artical page</h1>
  <p>
    <%= form.label :title %><br>
    <%= form.text_field :title %>
  </p>

  <p>
    <%= form.label :text %><br>
    <%= form.text_area :text %>
  </p>

  <p>
    <%= form.submit %>
  </p>
<% end %>

'''

schema.rb

'''

ActiveRecord::Schema.define(version: 2019_11_30_073138) do

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "text"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

end

'''

database.yml

'''

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

'''

yymmddttss_create_articles.rb

'''

 class CreateArticles < ActiveRecord::Migration[6.0]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :text

      t.timestamps
    end
  end
end

'''

i don't know where im making mistake. please when you reply it then make changes in above codes.

mercredi 27 novembre 2019

Write a complex Mongo query in Rails ORM

I want to convert mongo query to rails ORM query for the below json.

Rails query is:

db.collection.aggregate([
  {
    $match: {
      "data.toc.ge.ge._id": "5b"
    }
  },
  {
    $unwind: "$data.toc.ge"
  },
  {
    $unwind: "$data.toc.ge.ge"
  },
  {
    $group: {
      _id: null,
      book: {
        $push: "$data.toc.ge.ge._value"
      }
    }
  },
  {
    $project: {
      _id: 0,
      first: {
        $arrayElemAt: [
          "$book",
          0
        ]
      },

    }
  }
])

Please look at this as well:

https://mongoplayground.net/p/fb9IMkC1fCs

Collection is the corresponding class and this is what I've tried so far,

unwind2=  {'$unwind': "$data.toc.ge.ge"}
unwind3=  {'$unwind': "$data.toc.ge.ge.ge"}
group= {'$group': {_id: nil, book: {'$push': "$data.toc.ge.ge.ge._display_name"}}}
match= {'$match': {"data.toc.ge.ge.ge._id": "m121099"}}
project= {'$project': {_id: 0, 'mytopic': {'$arrayElemAt': ["$book",0]},}}

answer = collection.aggregate([match,unwind1,unwind2,unwind3,group,project]).to_a

mardi 26 novembre 2019

Form field doesn't get updated with AJAX

I'm trying to update the available rooms in a form, by making a POST request to my controller when arrival and departure dates are filled in the same form.

Unfortunately my inserted HTML doesn't seem to render, but I don't see where the bug is.

Code

reservations/new.html.erb

<%= simple_form_for [@hotel, @reservation] do |f|%>
  <div class="col col-sm-3">
    <%= f.input :arrival,
    as: :string,
    label:false,
    placeholder: "From",
    wrapper_html: { class: "inline_field_wrapper" },
    input_html:{ id: "start_date"} %>
  </div>
  <div class="col col-sm-3">
    <%= f.input :departure,
    as: :string,
    label:false,
    placeholder: "From",
    wrapper_html: { class: "inline_field_wrapper" },
    input_html:{ id: "end_date"} %>
  </div>

  <div class="col col-sm-4">
    <%= f.input :room_id, collection: @rooms, as: :grouped_select, group_by: proc { |room| room.room_category.name },  label:false %>
    <%#= f.input :room_id, collection: @room_categories.order(:name), as: :grouped_select, group_method: :rooms,  label:false %>
  </div>

  <%= f.button :submit, "Search", class: "create-reservation-btn"%>
<% end %>

script for reservations/new.html.erb

<script>
const checkIn = document.querySelector('#start_date');
const checkOut = document.querySelector('#end_date');
const checkInAndOut = [checkIn, checkOut];

checkInAndOut.forEach((item) => {
  item.addEventListener('change', (event) => {
    checkAvailability();
  })
})

  function checkAvailability(){

    $.ajax({
      url: "<%= rooms_availability_hotel_path(@hotel) %>" ,
      dataType: 'json',
      type: "POST",
      data: `arrival=${start_date.value}&departure=${end_date.value}`,
      success: function(data) {
        console.log('succes')
        console.log(data);
      },
      error: function(response) {
        console.log('failure')
        console.log(response);
      }
    });
  };
</script>

hotels_controller

def rooms_availability
  hotel = Hotel.includes(:rooms).find(params[:id])
  arrival = Date.parse room_params[:arrival]
  departure = Date.parse room_params[:departure]
  time_span = arrival..departure
  @unavailable_rooms = Room.joins(:reservations).where(reservations: {hotel: hotel}).where("reservations.arrival <= ? AND ? >= reservations.departure", arrival, departure).distinct
  @hotel_cats = hotel.room_categories
  @hotel_rooms = Room.where(room_category: hotel_cats)
  @rooms = hotel_rooms - @unavailable_rooms
  respond_to do |format|
    format.js
  end
end

def room_params
  params.permit(:arrival, :departure, :format, :id)
end

hotels/rooms_availability.js.erb

var selectList = document.getElementById('reservation_room_id')

function empty() {
  selectList.innerHTML = "";
}

empty();


    <% unless @rooms.empty? %>
      <% @hotel_cats.each do |cat|%>
        selectList.insertAdjacentHTML('beforeend', '<optgroup label=<%= cat.name %>>');
        <% cat.rooms.each do |room|%>
          <% if @rooms.include? room %>
            selectList.insertAdjacentHTML('beforeend', '<option value="<%= room.id %>"><%= room.name %></option>');
          <% end %>
        <% end %>
        selectList.insertAdjacentHTML('beforeend', '<optgroup>');
      <% end %>
    <% end %>

Print screen of form html

<div class="form-group grouped_select optional reservation_room_id">
  <select class="grouped_select optional" name="reservation[room_id]" id="reservation_room_id">
      <option value=""></option>
    <optgroup label="room category 1">
        <option value="6">1</option>
        <option value="7">2</option>
        <option value="8">3</option>
    </optgroup>
    <optgroup label="room category 2">
        <option value="16">1</option>
    </optgroup>
  </select>
</div>

logs

Processing by HotelsController#rooms_availability as JS
  Parameters: {"arrival"=>"2019-11-26", "departure"=>"2019-11-27", "id"=>"22"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ /Users/username/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
  Hotel Load (0.3ms)  SELECT  "hotels".* FROM "hotels" WHERE "hotels"."id" = $1 LIMIT $2  [["id", 22], ["LIMIT", 1]]
  ↳ app/controllers/hotels_controller.rb:125
  CACHE Hotel Load (0.0ms)  SELECT  "hotels".* FROM "hotels" WHERE "hotels"."id" = $1 LIMIT $2  [["id", 22], ["LIMIT", 1]]
  ↳ app/controllers/hotels_controller.rb:103
  RoomCategory Load (0.3ms)  SELECT "room_categories".* FROM "room_categories" WHERE "room_categories"."hotel_id" = $1  [["hotel_id", 22]]
  ↳ app/controllers/hotels_controller.rb:103
  Room Load (0.3ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."room_category_id" IN ($1, $2)  [["room_category_id", 4], ["room_category_id", 9]]
  ↳ app/controllers/hotels_controller.rb:103
  Room Load (0.4ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."room_category_id" IN (SELECT "room_categories"."id" FROM "room_categories" WHERE "room_categories"."hotel_id" = $1)  [["hotel_id", 22]]
  ↳ app/controllers/hotels_controller.rb:115
  Room Load (1.7ms)  SELECT DISTINCT "rooms".* FROM "rooms" INNER JOIN "reservations" ON "reservations"."room_id" = "rooms"."id" WHERE "reservations"."hotel_id" = $1 AND (reservations.arrival <= '2019-11-26' AND '2019-11-27' >= reservations.departure)  [["hotel_id", 22]]
  ↳ app/controllers/hotels_controller.rb:115
  Rendering hotels/rooms_availability.js.erb
  Rendered hotels/rooms_availability.js.erb (0.6ms)
Completed 200 OK in 53ms (Views: 19.3ms | ActiveRecord: 3.3ms)

ActiveRecord Associations(has_one) - Access parent object

class Parent < ApplicationRecord
  has_one: child
end


class Child < ApplicationRecord
  belongs_to :parent
end


childrens = Child.includes(:parent)

puts childrens.to_json
[{"id":1,"parent_id":1,"name":"Jack"},{"id":2,"parent_id":2,"name":"Oleg"}]

In this case, we can access parent object like this: child.parent

But it is not possible to access parent object in view. Is there any way to include parent objects in each child?

Thank you!

Rails Application keep heating pg_type and pg_attribute table how to reduse this call

I am using ruby ruby-2.1.2, Rails 4.1.3 with Postgres and we see application keep heating pg_type and pg_attribute table.

How to validate and see who calling this query?

Query 1 : SELECT oid, typname, typelem, typdelim, typinput FROM pg_type
Query 2 :  SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
                FROM pg_attribute a LEFT JOIN pg_attrdef d
                  ON a.attrelid = d.adrelid AND a.attnum = d.adnum
               WHERE a.attrelid = ?::regclass
                 AND a.attnum > ? AND NOT a.attisdropped
               ORDER BY a.attnum

dimanche 24 novembre 2019

Array returns first element blank in my Rails(3.2.11) multi-select

When I selected multiple values from select list then array returns the first value empty.

= f.select :assignedto, options_from_collection_for_select(User.all, 'name', 'name',f.object.assignedto),{}, { :multiple => true}

I tried with {:include_blank => false} and {:include_hidden => false} but this is not working for rails 3.2.11. I have many solutions to handle this empty value in the controller but I want to stop adding empty value in the array.

vendredi 22 novembre 2019

mardi 19 novembre 2019

one-liner for exit with message in capistrano

It is possible to have a one liner condition for exit with message?

if condition
  info "some message"
  exit
end

Can't start rails server after aws-sdk-3 installed

I know that there is a lot of such kind of questions, but still, I believe my case is slightly different. I recently decided to build in an AWS-S3 gem to my rails version 3 project. After the successfully aws-sdk gem have been installed, I've got an error message on rails server

/root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse/client/net_http/patches.rb:26:in `alias_method': undefined method `new_transport_request' for class `Net::HTTP' (NameError)
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse/client/net_http/patches.rb:26:in `apply!'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse/client/net_http/connection_pool.rb:10:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse.rb:34:in `require_relative'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/seahorse.rb:34:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `block in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `block in load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:597:in `new_constants_in'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-core-3.78.0/lib/aws-sdk-core.rb:2:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `block in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `block in load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:597:in `new_constants_in'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-resources-3.59.0/lib/aws-sdk-resources.rb:1:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `block in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `block in load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:597:in `new_constants_in'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:225:in `load_dependency'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/activesupport-3.0.19/lib/active_support/dependencies.rb:242:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/aws-sdk-3.0.1/lib/aws-sdk.rb:1:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `block (2 levels) in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `each'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `block in require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `each'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler.rb:120:in `require'
from /jasa/api/trunk/config/application.rb:7:in `<top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/railties-3.0.19/lib/rails/commands.rb:28:in `require'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/railties-3.0.19/lib/rails/commands.rb:28:in `block in <top (required)>'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/railties-3.0.19/lib/rails/commands.rb:27:in `tap'
from /root/.rbenv/versions/1.9.2-p320/lib/ruby/gems/1.9.1/gems/railties-3.0.19/lib/rails/commands.rb:27:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

I've tried both

gem 'aws-sdk', '~> 3'

and

gem 'aws-sdk-s3', '~> 1'

Thanks a lot. Any help will be appreciated.

lundi 18 novembre 2019

Write a function that returns the position or positions of the lowest valued integer and can handle this array or any array

figures = [-1, -7, 1, 5, -7, 0];

You are not allowed to use .map , each, max or other similar ruby methods. I got this question in a coding challenge and I was unable to produce a good answer.

def getArrayIndex(number, i) 
  n=1 
  if number[i] < number[i+=n] 
    puts number[i] 
  else 
    puts number[i+=n] 
  end 
end 
p getArrayIndex(figures, 0) 

Is it possible to create a single executable file of a Ruby on Rails project?

How to create a single executable file for any rails project. How to create a single executable file for any rails project.

samedi 16 novembre 2019

Devise Sign in and sign up form not working correctly

I've been trying to build a simple login and sign up screen but the user data isn't saving when i hit submit button. This is the page in devise At first eveything was going well and i got rib of most of the errors on my own but ive been stuck with this for a week.

When i fill out the form and hit submit the url changes to "http://localhost:3000/users/sign_up?user%5Busername%5D=Madmax_123&user%5Bfname%5D=Maxwell&user%5Blname%5D=Ross&user%5Bdob%5D=2000-01-22&user%5Bemail%5D=madmax_maxwell%40outlook.com&user%5Bpassword%5D=madmax123&user%5Bpassword_confirmation%5D=madmax123&commit=Submit#"

i wasnt sure is this was a problem so i checked to see is any users were created after in console with @user = User.first but it keeps coming up >=nil

  <div class="space">
    <div class="wrapper"> 
      <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
      <%= render "devise/shared/error_messages", resource: resource %> 

            <div class="container2 right-panel-active" id="container2">
              <div class="form-container2 sign-up-container2">
                <form action="#" id="form">
                </form>
              </div>
              <div class="form-container2 sign-in-container2">
                <form action="#" id="form">
                  <h3 class="h1">Create Account</h3><br><br><br><br>
                  <%= f.text_field :username, autofocus: true,  placeholder:"User Name", class:"input"  %>
                  <%= f.text_field :fname, placeholder:"First Name", class:"input" %>
                  <%= f.text_field :lname, placeholder:"Last Name", class:"input"  %>
                  <%= f.date_field :dob, placeholder:"Dte of Birth", class:"input"  %>
                  <%= f.email_field :email, autofocus: true, autocomplete: "email",  placeholder:"Email", class:"input"  %>
                  <%= f.password_field :password, autocomplete: "new-password",  placeholder:"Password", class:"input"  %>
                  <%= f.password_field :password_confirmation, autocomplete: "new-password",  placeholder:"Confirm Password", class:"input"  %><br><br>
                  <%=f.submit "Submit", class:"button" %>
                </form>
              </div>
              <div class="overlay-container2">
                <div class="overlay">
                  <div class="overlay-panel overlay-left">
                    <h3 class="h1">Already have an Account?</h3><br> <br>
                    <%= link_to "Login", new_user_session_path, class:"ghost2" %>
                  </div>
                </div>
              </div>
            </div>

      <% end %>
    </div>
  </div>

I added the variables to my migration.

class CreateEvents < ActiveRecord::Migration[5.1]
  def change
    create_table :events do |t|
      t.decimal :price
      t.date :date
      t.string :venue
      t.string :ename
      t.text :description
      t.text :time
      t.integer :ticket

      t.timestamps
    end
  end
end

allowed for the variables to be passed in my application controller

require "application_responder"

class ApplicationController < ActionController::Base
  self.responder = ApplicationResponder
  respond_to :html

  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected
    def configure_permitted_parameters
        devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :fname, :lname, :dob])

    end
end

Event controller

class EventsController < ApplicationController
    def index

    end

    def show
        @event = Event.find(params[:event_id])

    end

    def new

    end

    def create
        @event = Event.new(event_params)
        @event.save
        redirect_to  events_url events_path
    end

    private def event_params
        params.require(:event).permit(:ename, :price, :date, :venue, :description, :time, :ticket)

    end

end

any help would be greatly appreciated.

mercredi 13 novembre 2019

How to solve AbstractController::DoubleRenderError

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

Task not running using whenever gem but runs in command prompt

Task File

require 'report.rb'
require 'rake'

    namespace :daily_report do
      desc "Daily Parakh Report"
      task daily_operator_report: :environment do
        puts "Daily report generation started"
        Reports::Report.generate_csv
        puts "finished"
      end
    end

schedule.rb file

env :PATH, ENV['PATH']

set :output, "home/rajdeep/police-api/log/whenever.log"

every 1.day, :at => "06:46PM" do # Many shortcuts available: :hour, :day, :month, :year, :reboot
  rake "daily_report:daily_operator_report"
end

When the clock hits the speicified time in whenever.rb file nothing happens, the task doesn't run, even whenever.log file is not created.

when i run rake daily_report:daily_operator_report it works.

Ruby key getting replaced, instead of a new key created

ruby 2.5

I have the following code:

test = {'primer' => 'grey'}
layers = ["tan","burgundy"]
fillers = ["blue","yellow"]
layers.each do |l|
    fillers.each do |f|
      test[l] = {} if !test.respond_to?(l)
      test[l][f] = {} if !test[l].respond_to?(f)
    end
end

When I run it in irb, I get the following:

{"primer"=>"grey", "tan"=>{"yellow"=>{}}, "burgundy"=>{"yellow"=>{}}}

I am expecting:

{"primer"=>"grey", "tan"=>{"blue"=>{},"yellow"=>{}}, "burgundy"=>{"blue"=>{},"yellow"=>{}}}

Why does the first respond_to produce the key, when the second one, replaces the previous key?

What am I missing?

mardi 12 novembre 2019

Rails server exits automatically. This is what i see below:

Macs-MacBook-Pro:try_app mac$ rails server /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/object/duplicable.rb:85: warning: BigDecimal.new is deprecated; use BigDecimal() method instead. => Booting WEBrick => Rails 4.2.3 application starting in development on http://localhost:3000 => Run rails server -h for more startup options => Ctrl-C to shutdown server /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated Exiting Traceback (most recent call last): 8483: from bin/rails:3:in <main>' 8482: from bin/rails:3:inload' 8481: from /Users/mac/try_app/bin/spring:15:in <top (required)>' 8480: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:inrequire' 8479: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in require' 8478: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in' 8477: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in load' 8476: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/spring-2.1.0/bin/spring:49:in' ... 8471 levels... 4: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>' 3: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in ' 2: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>' 1: from /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in ' /Users/mac/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in ': stack level too deep (SystemStackError)

jeudi 7 novembre 2019

Subtracting month from date is not giving correct value in ruby?

i am trying to subtract the month from Date its not giving accurate result

end_date = Date.parse("30-09-2019")
end_date - 1.months

returns 30 - aug - 2019

example 30-09-2019 - 1.month to give 31 - 08 - 2019
example 15-09-2019 - 1.month to give 14 - 08 - 2019

mercredi 6 novembre 2019

How to write url path for a .svg picture in css file on ruby on rails

I have a background-image with a svg file but it doesn't work at all, here is my css file :

&[data-icon=hourglass]::before {
    background-image: url("../../icons/hourglass.svg");
}

Do you know how to fix it ?

404 (Not Found) on my icon.svg - Ruby on rails app

I have an icon in my folder app > assets > medias > logo-footer.svg In my code it looks like this :

<img loading="lazy" class="footer__logo" src="app/assets/medias/logo-footer.svg" alt="Logo">

In my application I have an error in my console : GET http://127.0.0.1:3000/assets/icons.svg 404 (Not Found).

How can I set the right path to this icon.svg ?

Does call_backs with same name in parent and child classes need not to be called again

I had two methods with same name which is present in both parent and child class. But I the callback before_filter: method_name is called only in parent class and the before_filter: is not present in child class. But load_object is called in child class without call_back itself.

class Parent

before_filter: call

def call // end

end

class child < Parent

def call //But the method is called here without call_back end

end

There is no class is inherited from child.

Include scripts folder in my ruby on rails application

I try to integrate a script folder (with different file in .ts), located in my folder "javascript", in my ruby on rails application but when I make an alert in my index.ts, it doesn't work.

I have the balise javascript pack tag in my application.html.erb

<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

I installed the gem 'typescript-rails' to run my .ts files I also tried to rename the file in .js.ts but it doesn't work either.

Do you have any idea how to run those files ?

lundi 4 novembre 2019

ActionView Template Error: Missing host to link to settings with no effect

I am updating an old rails 3 application to rails 4. When I run my tests with test unit I am getting the following error in my actionmailer:

ActionView::Template::Error: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

After some research I found that it requires the options

# in: environment.rb 
# Set the default host and port to be the same as Action Mailer.
Rails.application.default_url_options = Rails.application.config.action_mailer.default_url_options

# and in each environment an entry like this: 
# environments/test.rb 
config.action_mailer.default_url_options = { host: 'localhost', port: '3000' }

While I can confirm these settings are set in the rails console. The error does not go away.

2.0.0-p648 :002 > Rails.application.default_url_options
 => {:host=>"localhost", :port=>"3000"} 
2.0.0-p648 :003 > Rails.application.config.action_mailer.default_url_options
 => {:host=>"localhost", :port=>"3000"} 

dimanche 3 novembre 2019

Powered By Ruby on Rails

I had a site created. The developer thought it might be a good idea to put his link in the Powered By link at the bottom of my site How can i remove this? I have tried to remove it but i am not too familiar with Rails.

jeudi 31 octobre 2019

Print Object attributes after creation in rails

I am new to rails and I want to jut print in the console the name of the lastly created record of Document. For this I am using in the model file, after? create callback.

Anyway I can not get the name displayed in the console after I run a procedure of creation. How can this be done to be able to display the name of the lastly created record of type Document?

 class Document < ApplicationRecord
  belongs_to :storage

  after_create :my_function

  def my_function
    puts Document.name
  end
 end

Setting default headers in Rails3 applications

I know that you can set default headers application wide in config/application.rb for Rails4+ apps but what is the accepted method in older versions of Rails, as in Rails3?

At the moment I am setting them in application_controller.rb as a before_filter method, but I think this is a bad practices and performance -impacting

https://edgeguides.rubyonrails.org/security.html?utm_source=twitterfeed&utm_medium=twitter#default-headers

How to access key, value in json / ruby

I have a json file like this, and I try to display the different value in my html:

{
    "testimonials": [
        {
            "office": "Test",
            "authors": "Benjamin",
        },
        {
            "office": "consultant",
            "authors": "Maxime ",
        },
        {
            "office": "DAF",
            "authors": "Alexandre",

        },
        {
            "office": "CEO",
            "authors": "Raphaël",
          },
        {
            "office": "Consultant",
            "authors": "Alexis",
        },
        {
            "office": "CEO,",
            "authors": "Sylvain",
        }
    ]
}

Could someone help me, for example, to access to display the value 'Alexis'

mercredi 30 octobre 2019

Multiple validates with :on in ruby

Hey I have a doubt if there is multiple validate in a line if :on at last whether all the validation are applicable to the :on or only the last validation.

//code validate :trial_account, :limit_for_account, on: :check_trial

// Whether only limit_for_account is validated on check_trial or both.

How to add count with active record association?

My Requirement is to send the count size of the database with active record association

I am trying to limit the size of record and want to load more options and clicking on load more will give all records

records = company.public_send(table).joins(:customer).where(customer_id: ids).order(sorting)
#records = records.count(:id) #300
records = records.limit(5)

This return me active record, along with this i want to send entire size of record How can i do it

mardi 29 octobre 2019

rake db:setup shows rake aborted! KeyError: key not found: "URL_HOST" error

i have rails app ubuntu 18.04. bundle install run successful but when i run rake db:setup it shows

rake aborted! KeyError: key not found: "URL_HOST" /var/www/myapp/code/config/environments/production.rb:71:in fetch' /var/www/myapp/code/config/environments/production.rb:71:inblock in ' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/railtie.rb:210:in instance_eval' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/railtie.rb:210:inconfigure' /var/www/myapp/code/config/environments/production.rb:3:in <top (required)>' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:inrequire' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:in block in require' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:240:inload_dependency' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:in require' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/engine.rb:598:inblock (2 levels) in ' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/engine.rb:597:in each' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/engine.rb:597:inblock in ' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:30:in instance_exec' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:30:inrun' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:55:in block in run_initializers' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:44:ineach' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:44:in tsort_each_child' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:54:inrun_initializers' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/application.rb:352:in initialize!' /var/www/myapp/code/config/environment.rb:5:in' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:in require' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:inblock in require' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:240:in load_dependency' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:inrequire' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/application.rb:328:in require_environment!' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/application.rb:457:inblock in run_tasks_blocks' /home/myappuser/.rvm/gems/ruby-2.5.0/gems/rake-13.0.0/exe/rake:27:in <top (required)>' /home/myappuser/.rvm/gems/ruby-2.5.0/bin/ruby_executable_hooks:24:ineval' /home/myappuser/.rvm/gems/ruby-2.5.0/bin/ruby_executable_hooks:24:in `' Tasks: TOP => db:setup => db:schema:load_if_ruby => environment (See full trace by running task with --trace)

Need help

How to do if condition check for value A against multiple values in Ruby on Rails?

I have a normal if condition. I have to check

if A IN (:B, :C ) {
 do something
}

But it is not working.

Call an action on button click in ruby on rails

I have an action defined in my lib directory. The action is used to send a get request in the server. I want to execute the function on button click. How can I do this? I know this is not the right approach. I am new to rails.

show_document.rb (in lib directory)

class Legaldoc::ShowDocument

def view_document(sessionID, token_document)
    require 'rest-client'
    require 'zip'
    res = RestClient::Request.execute(
        :method => :get,
        :url => "http://myurl.com",
        :headers => {
            :ldsessionId => sessionID,
        }
    )
  end
end

in my view file

<%= link_to 'Button', '#', :onclick => "view_document(sessionID, token_document)" %>

Rails3 create a global variable throughout application upon initialization

Currently we have a method in application_controller.rb which initialises a global variable or returns its value if it has been initialized.

Problem is this is being called upon each request, and its redundant because the variable is initialized after the first request.

How can I move this method to application.rb and have it run once upon Rails' initialisation

    config.after_initialize do
      begin
        @global_user = User.find(100)
      rescue => e
        Rails.logger.info "Error finding the Global User"
      end
    end

What is the correct way to fix bundler not finding compatible versions

I have an old rails 3 application which I want to update to rails 4 at the moment. I removed the Gemfile.lock manually and changed the Gemfile to require rails in version "4.0.0" before running a fresh "bundle install". I was getting several messages that bundler was not able to find compatible versions.

I am using ruby 2.0.0 here installed with rvm on a linux system.

I installed rails 4.0.0 manually using

gem install rails -v 4.0.0

And then I tried again with

bundle install

This is one example of the messages that pop up:

Bundler could not find compatible versions for gem "activerecord":
  In Gemfile:
    activerecord-import (~> 0.4.1) was resolved to 0.4.1, which depends on
      activerecord (>= 3.0)

    authlogic (~> 3.3.0) was resolved to 3.3.0, which depends on
      activerecord (>= 3.2)

    delayed_job_active_record (~> 4.0.0) was resolved to 4.0.3, which depends on
      activerecord (>= 3.0, < 5.0)

    rails (= 4.0.0) was resolved to 4.0.0, which depends on
      activerecord (= 4.0.0)

Due to the manual install of rails 4 I have activerecord in version 4.0.0 in my gems available. Why does it come up with that message? From my interpretation of the listed activerecord versions the dependency should be fulfilled with version 4.0.0? It is in the listed range between 3.0 and less than 5.

samedi 26 octobre 2019

Build A Ruby program code or Rubymine code with following:

Chapter 9 Assignment

CIS 116 Introduction to Programming

Build a Ruby code or Rubymine code with following:

You work for a software development company that wants to build and sell games that run in Windows. The company is in the process of creating a basic game engine. It wants everything to be object-oriented, so it needs to build the various classes that will be used in any of the games built in the future.

You have been assigned the task of building the Player class based on the specifications listed below. The class will be further developed in the future, but this initial class will help the team get started. Put all of your code in the same source file and name your file Ch9Asg.rb.

  • Create a Player class with a name and a health attribute. The health attribute must be an integer between 0 and 100. A Player with a health value of 100 is in excellent condition, and a Player whose health is 0 is essentially dead.

  • Create a class constructor that accepts two arguments that are assigned to the attributes.

  • Create a method that sets the health attribute given a value. If an attempt is made to set it below 0, set it 0; likewise, if an attempt is made to set the value higher than 100, set it to 100.

  • Create an attack() method that accepts a Player object named opponent as a parameter. Within the method, generate a random number between 0 and 25. If the value falls between 0 and 15, reduce the opponent’s health by that amount. If the value is over 15, consider the attack a failed attempt.

  • As the loop repeats, keep the user informed with what’s going on by showing the name and health of each player.

To test your class, create two Player objects, p1 and p2; give them different names. Build a loop that has p1 attacking p2; then, if p2 is still alive, it should attack p1. The loop should keep repeating until either p2 or p1 is dead, i.e. has a health value of 0. Display the winner at the end.

Submit your Ch9Asg.rb file on or before the due date. Be sure to comment your Player class well so that other programmers who use it know how it works and how to use it.

Is there a simple way I can query a Ruby on Rails join table in my view

New to RoR and struggling to make my table join work in my application views. I have 2 models Category and Pricing. They are joined through CategoryPricings .

Concept is a single Category can have multiple Pricings ( 4 pricing levels for the category ).

Where I am struggling is presenting the pricing information in my view when a category is selected.

So if I chose category (with id = 3) I would like the 4 price levels for that category to be presented.

My Models

 create_table "categories", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "pricings", force: :cascade do |t|
    t.string "overview"
    t.text "description"
    t.integer "delivery_time"
    t.integer "price"
    t.integer "pricing_type"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "category_pricings", force: :cascade do |t|
    t.bigint "category_id", null: false
    t.bigint "pricing_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["category_id"], name: "index_category_pricings_on_category_id"
    t.index ["pricing_id"], name: "index_category_pricings_on_pricing_id"
  end

My Controllers

class UsersController < ApplicationController

  before_action :authenticate_user!

  def dashboard
    #@user = User.find(params[:id])
    @categories = Category.find(params[:id])
  end

  def show
    @user = User.find(params[:id])
    @user_listings = @user.listings.paginate(:page => params[:page], :per_page => 5)
  end

  def index
    @user = User.paginate(:page => params[:page], :per_page => 5 )
  end

  def set_user
    @user = User.find(params[:id])
  end


  def update
    @user = current_user
    if @user.update_attributes(current_user_params)
      flash[:notice] = "Saved"
    else
      flash[:alert] = "Cannot update..."
    end
    redirect_to users_dashboard_path
  end

  private
  def current_user_params
    params.require(:user).permit(:from, :about, :status, :language, :avatar)
  end

  def category_params
    params.require(:category).permit(pricings: [])
  end

  protected

  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:full_name, :username, :email, :password, :password_confirmation)}
  end

  # If you have extra params to permit, append them to the sanitizer.
  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: [:attribute])
  end

  #The path used after sign up.
  def after_sign_up_path_for(resource)
    users_dashboard_path
  end

  def after_sign_in_path_for(resource)
    users_dashboard_path
  end

  def update_resource(resource, params)
    resource.update_without_password(params)
  end
end


  # def after_sign_in_path_for(resource)
  #   users_dashboard_path
  # end

  # The path used after sign up for inactive accounts.
  # def after_inactive_sign_up_path_for(resource)
  #   super(resource)
  # end

My Views Code

<footer class="card-footer">
    <% @categories.name %>

      <a class="has-text-danger is-block card-footer-item has-text-right">

      </a>
  </footer>

I am unfortunately not able get my view working so I can get the the list of prices for each category. Any help appreciated

jeudi 24 octobre 2019

iterate through elements in array within active record

I am trying to do a comparison and return a statement whether the item is inside of the array or not. Menu is an object that I have in active record which is composed of 3 attributes, the menu type, meal and the restaurant id. For the meal attribute I had a variable set to it which is actually an array that contains the names of meals.

In my code when I do puts"#{menu.meal}" I get back...

["Pancakes W/ Eggs and Bacon", "Bacon Egg and Cheese", "Oatmeal W/ Raisins", "Scrambled Eggs W/ Grits", "Blueberry Waffles W/ Syrup", "Chocolate Chip Pancakes W/ Sausage", "Yogurt Muffin"]

which is the array of meals that I have set in my seeds file. In the code below what I am trying to do is when the user enters the meal that it wants I want to search through all the meals if it exits, and if it does then the user can proceed and if not I want to output an error message saying that it does not exist.

 puts "What meal would you like to order"
 item_meal = gets.chomp


 menus_meals = res.menus.select do |menu|
   binding.pry
   menu.meal == item_meal

lundi 21 octobre 2019

Ruby: Check multiple keys in hash and delete it

I need to check if the given both keys is present in hash. Checking is not the problem here but one of the keys may not be present and can return false. I need to delete only the keys that are present.

if model_changes.has_key?(name)
   model_changes.delete(name)
end  

if model_changes.has_key?(id)
   model_changes.delete(id)
end

Instead of writing in two separate conditions is it possible to combine and delete the present key

Why ransank doesn't work with flutter chopper?

Can ransank work with flutter chopper?

My flutter project using chopper to call api server, which written using Rails.

   @Post(path: "orders_list")
      Future<Response> getOrderList(@Field('token') String authToken,  @Field('q[flow_gteq_any]') int flow,
            @Field('q[flow_lteq_any') int flow2);

I want server return data based on flow_gteq_any and flow_lteq_any, but it returns all data to me instead.

dimanche 20 octobre 2019

Rails Routing Clash When Rendering Static Pages

I have a routing clash. After moving all of my blog posts from /posts/:id to /:id (which is great), I now have an issue where my static pages don't contain an ID, so they aren't rendering. I don't want to have to process them through my posts controller.

Here's what I currently have in my routes.rb file:

  resources :posts, only: [:index, :create, :edit, :new, :destroy]
  get '/:id' => 'posts#show', :as => 'custom_url'
  match '/posts/:id' => redirect('/%{id}', status: 301)

But then these now don't work...

  match '/privacy' => 'static#privacy'
  match '/terms' => 'static#terms'

I have a controller called static_controller.rb which I can use if I need to. How can I jump over the /:id match.

samedi 19 octobre 2019

Date conversion in UTC

I am working ruby on rails. In that I have a doubt in date conversion from current timezone to UTC.

The date conversion function is

function date_conversion(date){
    out = moment(date, "DD/MM/YYYY").format('YYYY-MM-DD')
    var utc_time = moment.tz(out, zone).tz('UTC').format();
    return utc_time;
}

Here params date let as "12/10/2019" which is in string format and let the zone is ""Asia/Kolkata".

After executing the date_conversion function the values are

   out = moment(date, "DD/MM/YYYY").format('YYYY-MM-DD') 

The output of out = "2019-10-12"

   var utc_time = moment.tz(out, zone).format();

The value of utc_time is 2019-10-12T00:00:00+05:30. There is no problem while using above. But when i am trying to convert to UTC as below

    var utc_time = moment.tz(out, zone).tz("UTC").format();

I got 2019-10-11T18:30:00Z. In this situation I need of date in UTC but that date not to be changed. Please tell anybody some idea for this

vendredi 18 octobre 2019

cant rake db:migrate undefined method erorr

Hi guys I am new to rails and just getting started. Everytime I try to run rake db:migrate I get this(trace):

rake db:migrate == CreateModelNames: migrating =============================================== -- create_table(:model_names) rake aborted! StandardError: An error has occurred, all later migrations canceled:

undefined method feldtyp' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x7f729807cfa8>./db/migrate//20191018075455_create_model_names.rb:4:inup_without_benchmarks' ./db/migrate//20191018075455_create_model_names.rb:3:in up_without_benchmarks' (__DELEGATION__):2:insend' (DELEGATION):2:in `migrate' Tasks: TOP => db:migrate (See full trace by running task with --trace) david@david-desktop:~/Railsprojekte/david$ rake db:migrate --trace** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:migrate == CreateModelNames: migrating =============================================== -- create_table(:model_names) rake aborted! StandardError: An error has occurred, all later migrations canceled:

undefined method feldtyp' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x7f61a32f62f8>./db/migrate//20191018075455_create_model_names.rb:4:inup_without_benchmarks' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/schema_statements.rb:104:in create_table' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/mysql_adapter.rb:445:increate_table' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:346:in send' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:346:inmethod_missing' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:326:in say_with_time' /usr/local/lib/ruby/1.8/benchmark.rb:293:inmeasure' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:326:in say_with_time' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:342:inmethod_missing' ./db/migrate//20191018075455_create_model_names.rb:3:in up_without_benchmarks' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:280:insend' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:280:in migrate' /usr/local/lib/ruby/1.8/benchmark.rb:293:inmeasure' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:280:in migrate' (__DELEGATION__):2:insend' (DELEGATION):2:in migrate' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:480:inmigrate' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:556:in call' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:556:inddl_transaction' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:479:in migrate' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:466:ineach' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:466:in migrate' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:394:inup' /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/migration.rb:377:in migrate' /usr/local/lib/ruby/gems/1.8/gems/rails-2.2.2/lib/tasks/databases.rake:111 /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:240:incall' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:240:in execute' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:235:ineach' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:235:in execute' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:179:ininvoke_with_call_chain' /usr/local/lib/ruby/1.8/monitor.rb:242:in synchronize' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:172:ininvoke_with_call_chain' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/task.rb:165:in invoke' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:150:ininvoke_task' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:106:in top_level' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:106:ineach' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:106:in top_level' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:115:inrun_with_threads' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:100:in top_level' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:78:inrun' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:176:in standard_exception_handling' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/lib/rake/application.rb:75:inrun' /usr/local/lib/ruby/gems/1.8/gems/rake-10.4.2/bin/rake:33 /usr/local/bin/rake:26:in `load' /usr/local/bin/rake:26 Tasks: TOP => db:migrate

My code is this:

class CreateModelNames < ActiveRecord::Migration def self.up create_table :model_names do |t| t.feldtyp :feld_name

  t.timestamps
end

end

def self.down drop_table :model_names end end

Any help would be apreeated :)

LG

jeudi 17 octobre 2019

Rails Change common id of simple_form_for

I want to change form common name in rendering side

_from.html.haml
..
= f.simple_fields_for Image.new do |form|
      = render 'avatar_fields', f: form
..

_avatar_fields.html.haml
..
     = f.hidden_field :imageable_type
..

This is rendering like

<input id="product_image_imageable_type" name="product[image][imageable_type]" type="hidden">

But i want to render like this

<input id="product_logo_attributes_imageable_type" name="product[logo_attributes][imageable_type]" type="hidden">

I don't want to edit my '_avatar_fields.html.haml' screen. Because it's common html.

Any suggestion please..?

mercredi 16 octobre 2019

Ruby Rspec should_not_receive not working

For this below code snippet:

@by_hidden.should_not_receive(:by_limit).with(100).and_return(@by_limit)

I am facing error as

@by_hidden.should_not_receive(:by_limit).with(100).and_return(@by_limit)
       (Double Object).by_limit(100)
           expected: 1 time with arguments: (100)
           received: 0 times with arguments: (100)

Any information on this shall be appreciated.

Instance Variable in Ruby Resetting as Nil

My instance variables gets turned back to nil, even though it was set in a separate function that is called.

I've tried printing out before and after values for the instance variable, and have seen where it turns to nil. It's quite puzzling though. Attaching an example (https://repl.it/repls/FirebrickPresentKeyboard) also below:

class Test
  def process 
    return if a.nil? && b.nil?
    puts @some
  end

  def a
    @some = nil
    return true
  end

  def b
    @some = "abc"
    return false
  end

end

class Test2
  def process 
    return if c.nil?
    puts @hello
  end

  def c
    @hello = "hello"
    return true
  end
end

t = Test.new
t.process

t2 = Test2.new
t2.process

In the Test class, I expect @some to print "abc" since it is set during the "b" function. However, it prints nil.

In the Test2 class, I expect @hello to print "hello" and it certainly does.

mardi 15 octobre 2019

Halm ruby on rails : error Encountered a syntax error while rendering template:

I try to execute the following code but I have the error "Encountered a syntax error while rendering template:" and i can't fix it could someone help my ?

Here is my view :

%section
    %article
        - if @toss % 2 === 0
            %p the player #{@player_one.name} start the fight !
        - else 
            %p the player #{@player_two.name} start the fight !

        - while @hp_player_one > 0 && @hp_player_two > 0 
            - @hp_player_one -=  @player_two.attack
                %p  There is only #{@hp_player_one.to_s} point to #{@player_one.name}
            - @hp_player_two -=  @player_one.attack
                %p  There is only #{@hp_player_two.to_s} point to #{@player_two.name}
                -if @hp_player_one <= 0 && @hp_player_two > 0
                    %p #{@player_one.name} lost 
                -elsif @hp_player_two <= 0 && @hp_player_one > 0
                    %p #{@player_two.name} lost 
                -else 
                    %p draw ! 

lundi 14 octobre 2019

Faraday Json validation before .post

Currently using Faraday to do some http request to certain api. I want to validate the body and header at step of .post. However, when calling the .post the information is initialize and send asynchronously. (I did receive the Json schema validation from the API receiver side)

So! I was wondering if it is possible to setup a schema validation at the step of .post

I am able to use the Faraday_Middleware using the def call to intercept, but was it possible to turn the request into Json form and validate them?

how to "get" with Ruby on rails form

I try get 2 players from a list that i created, all I need is to get all the informations about those 2 players (name, descrption etc...) and once i have selected both, I need to be redirected to /fight path. My form doesnt work and I don't understand why. Could someone help me please ?

Here is my view :

<%= form_tag ("/fight", :method => "get") do %>
  <%= label_tag :player1 %>
  <%= select_field :character, @characters.collect{|u| [u.name, u.id]} %>
  <%= label_tag :playe2 %>
  <%= select_field :character, @characters.collect{|u| [u.name, u.id]} %>
  <%= form.submit 'Fight' %>
<% end %>

My pages_controller

def index 
  @characters = Character.all
end

And my routes

get 'fight' => 'pages#index'

dimanche 13 octobre 2019

Premailer-rails stopped working on rails version 3.2.22

I have included " gem 'premailer-rails'" in my Gemfile.

And include stylesheet like this : <%= stylesheet_link_tag "mailers/test" %> in mailer layout file, where path for css file is : app/views/layouts/test.html.erb.

For few days this configuration was working fine. But now it stopped , I an unable to figure out the reason.

My rails version is 3.2.22

Followed this link for my project : https://hackernotes.io/a-production-ready-rails-5-email-workflow-with-mailer-previews-premailer-and-activejob/

In Gemfile.lock : premailer (1.11.1) addressable css_parser (>= 1.6.0) htmlentities (>= 4.0.0) premailer-rails (1.10.3) actionmailer (>= 3) premailer (~> 1.7, >= 1.7.9)

Any leads will be very helpful.

samedi 12 octobre 2019

PG::Error: Wait on socket error (WaitForMultipleObjects)

I am using Rails 3 app on windows with ruby 1.9.3p551 and postgres(9.1.3) database. While running load test for the app, we're observing few request failure with error PG::Error: Wait on socket error (WaitForMultipleObjects) originating from activerecord-3.2.11/lib/active_record/connection_adapters/postgresql_adapter.rb:1153:in 'async_exec'.

Tried increasing connection pool of Postgres and checkout_timeout but same error keeps on coming during load test. Any idea/help on what could cause this issue will be very helpful. also, What could be the solution for this as at this time, we cant migrate to different version of ruby.

Thanks

jeudi 10 octobre 2019

Reading gz file in Ruby using Zlib. Zlib::GzipReader is reading only the first line of the file and not all lines

I have a gz file that I wanna parse. I am using Zlib::GzipReader library to open it. In console I have the file like this:

164] pry(main)> file
=> #<Zlib::GzipReader:0x00007fadbbfa5a08>
[166] pry(main)> Zlib::GzipReader.open(file.path){|gz| print gz.read }
"Date","Connection type code","Connection id","Currency","Impressions","Campaign","Traffic source","Clicks","Cost (EUR)","Country"
=> nil

Notice that, after reading the file and printing. I just got the first line but in fact, the file contains lots of lines and I wanna have them all

Rails 3 random database exceptions using postgres

One of our application is built on Rails 3 which uses postgres as database. We observe that while doing load test i.e continuously submitting request, there are random exceptions related to database (comes from postgres_adapter):

1. PG::Error: Wait on socket error (WaitForMultipleObjects):
2. NoMethodError: undefined method `result_error_field' for nil:NilClass: 

I am not able to find any reference on cause of these issues as they're coming at different points. Any help on how to avoid this or solve this would be helpful.

Thanks

mercredi 9 octobre 2019

on sign up if email already exist then render user on specific page with where i can display some messege

i just want to send confirmation instructions to user again if email already exist.

Thats what i've implemented, it just let user to sign Up if email is unique. if email already exist it just don't do anything.

class RegistrationsController < Devise::RegistrationsController
  layout 'pages'
  def new
    build_resource
    yield resource if block_given?
    respond_with resource
  end

  def create
    build_resource(sign_up_params)
    admin = User.create(first_name: "")
    resource.authenticatable = admin
    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: accounts_get_started_path(resource)
      end
    else
      byebug
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource
    end
  end

  def edit
    super
  end

  def update
    super
  end

  def destroy
    super
  end
end`enter code here`

mardi 8 octobre 2019

Duda sobre búsqueda en base de datos

Soy nuevo programando en Ruby on Rails y quisiera saber si me pueden ayudar con lo siguiente: Estoy intentando realizar la búsqueda de un estudiante con su cédula en la base de datos para saber cuáles y cuántos cursos ha realizado. La idea es que en la vista "Index" se digite el número de cédula y en la vista "Show" aparezca un listado con todos los cursos que ha realizado. Cabe resaltar que pueden aparecer uno, dos o más cursos.

He intentado realizar la búsqueda con la forma form_tag, con el método find y aún no lo he logrado.

Se espera que aparezca el listado de cursos realizados al buscar la cédula, pero no me está mostrando nada. Cabe resaltar que sí hay conexión a la base de datos y sí hay datos de ejemplo para mostrar.

How to remove [Thr-1] from Rails logs?

My logs are prepended with [Thr-1] or [Thr-2] and I can't figure out how to disable this behavior. I assume that they are the thread names, but I'm unsure.

lundi 7 octobre 2019

Rails Server exiting automatically immediately after start in newly cloned github repo

I have cloned a github repo and run the command bundle install, but after when I am starting the rails server it shows me the following error :

error message

What is the use of ! in rails

What is the use of ! in rails?

Especially in this line: From HArtl tutorial

users = User.order(:created_at).take(6)
50.times do 
    content = Faker::Lorem.sentence(5)
    user.each { |user| user.microposts.create!( content: content )}
end

Basically this is creating tweets/microposts for 6 users.

I am really wondering why need to use !

samedi 5 octobre 2019

How to resolve jekyll sass-converter error in Installation in Windows

I want to install jekyll, for that i have install ruby on rails (ruby version 2.3.3 and rails version) but the error i am facing in install is that jekyll sass-converter requires ruby version 2.4 from this link http://railsinstaller.org/en. I have downloaded and installed the other version 2.4 as well but got the error with version 2.5. How should I tackle this please guide me in this regard?

mardi 1 octobre 2019

asdf message "No version set for command rails" when running Rails server

I am trying to run my rails server (rails s) in my Rails 3.2.13 application after having updated my Ruby version in /.ruby-version and /.tools-versions, but get the following message:

`you might want to add one of the following in your .tool-versions file:

ruby 2.2.4`

However, I had updated ruby in both version files to 2.3.0 and it is reflected in both. When I type asdf which ruby the ruby version is also 2.3.0.

I'd like help understanding why rails s prompts this asdf message, and what I'm missing with how to fix it so that I can run the rails server.

HTTP parse error, malformed request (): #

i am running this on my localhost:3000 i am in the part in which i would signup and recieve a email activation and the email activation is in HTTPS, so im getting parse error. (Michael Hartl tutorial)

system:

I am running in windows 10.

ruby: bin: F:/Program/RailsInstaller/Ruby2.3.3/bin/ruby.exe version: ruby 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]

rails: bin: F:/Program/RailsInstaller/Ruby2.3.3/bin/rails.bat version: Rails 5.1.7

after creating the key and cert and bind it to my localhost i am getting an error below

rails s -b 'ssl://localhost:3000?key=/.ssl/localhost.key&cert=/.ssl/localhost.crt'

C:/Ruby23/lib/ruby/gems/2.3.0/gems/puma-3.11.0/lib/puma/binder.rb:149:in `check': SSL not available in this build (StandardError)

I have read that i need to install RubyInstaller-2.4 and newer to resolve this. but i am having issue on upgrading or pointing it to the new Rubyinstaller. Can someone guide me on what is the best setup in a windows OS or guide me on how to upgrade the rubyinstaller to 2.4, i have installed the latest 2.6 version but when i point it to this, it is giving me that the gems are missing.

dimanche 29 septembre 2019

Active record lookup - find_by_inventory_product_id is intermittently slow inspite of adding index

I have a simple new API endpoint, which involves querying my newly setup and populated table - inventory_products.

The schema of inventory_products table is :

CREATE TABLE `inventory_products` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `inventory_product_id` binary(16) DEFAULT NULL,
  `product_id` binary(16) DEFAULT NULL,
  `status` enum('ACTIVE','INACTIVE','DELETED') DEFAULT 'ACTIVE',
  `priority` int(11) DEFAULT '0',
  `inventory_service_id` tinyint(3) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uc_inventory_product_id` (`inventory_product_id`),
  KEY `idx_product_status` (`product_id`,`status`)
) ENGINE=InnoDB AUTO_INCREMENT=76312817 DEFAULT CHARSET=utf8;

The API endpoint mainly does the below:

def lookup_inventory_service_id
    return render_error_response(AUTH_ERROR, {status: 403}) unless client.name == PERMITTED_NAME

    ip_fetch_start = Time.now
    inventory_product = InventoryProducts.find_by_inventory_product_id(resource_attributes[:inventory_product_id])
    Rails.logger.info({inventory_product_id: resource_attributes[:inventory_product_id], inventory_product_fetch_time_ms: (Time.now - ip_fetch_start)*1000}.as_json)
    return head :not_found unless inventory_product
....

Problem: The inventory_product lookup (find_by_inventory_product_id) is the standard function provided by Rails's ActiveRecord (I have not overwritten it in my model). This function takes from 10ms to sometimes even 650ms (found this from the logs I added). Why would this take up so much time in some cases and so less time in some other in spite of Mysql index existing on the column used in the lookup?

I have mentioned inventory_product_id as a unique key in my schema and the MySQL query triggered by the above function is using inventory_product_id as an index from the below explain statement.

explain SELECT inventory_products.* FROM inventory_products WHERE inventory_products.inventory_product_id = 0x3a288cdce78d44618eadd72e240f26a4 LIMIT 1

id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE inventory_products const uc_inventory_product_id uc_inventory_product_id 17 const 1 NULL

Is there something wrong in my schema? Do I explicitly need to mention inventory_product_id as a mysql index in the schema? Something like:

KEY `idx_product_status` (`product_id`,`status`)

Thanks, in advance!!

I use Mysql 5.6 and rails - 3.2.8. Also, my rails application runs on a tomcat server (version - Apache Tomcat/7.0.16) inside jruby (1.7.0)/