mercredi 31 juillet 2019

Ruby - Delete a value from array

When I try to delete a value from array and map with same array object its not working getting error undefined method 'delete'.

test = ["ab","cd","ef"] test.map.delete("ab")

NoMethodError (undefined method `delete' for #)

mardi 30 juillet 2019

I need to display properly my form.text_area with Simple_format

I need to display properly my form.text_area with CR (carriage return when the enter key is press(in display show)

I have tried to use simple_format(<%= form.text_area :description %>) but it's not work.

<!-- Description -->
      <div class="field">
        <label>Description : </label>
         <div class="<%=ticket.errors[:description].empty? ? 'field' : 'field error'%>">
           simple_format(<%= form.text_area :description %>)
         </div>
      </div>

I wish you can help me, thanks.

How to list the attribute names of a rails request object without seeing nested values

When I am debugging the request spec for a particular rails route, I often want to see what response a particular route produced. So, I insert the line binding.pry into my request spec, so that I can look at the response object. However, when I print response to the console, the shell prints the full object and all its recursively nested attributes. This is over 1000 lines long and consequently very hard to read. I would like to see just the top-level attribute names of that object, how can I do so?

Is there a ruby or rails equivalent to python's function dir(some_object)?

lundi 29 juillet 2019

run factorybot and create an array of json with specific values

I am learning Ruby on rails and stuck on this issue.

I have to use a FactoryBot, and from the generated value, take only 2 values out and write into an array of JSON. I also need it pretty printed.

So far I got till this

   test = FactoryBot.create(:test)

   foo = {
      'a' => test.id,
      'b' => test.email
    }

    companies_json = []
    puts "hello" << foo.to_json
    out_file = File.open("test.data.ts", "w+") do |f|
       companies_json << foo.to_json
       f.puts("DATA =")
       f.puts(JSON.pretty_generate(companies_json))
       f.close
    end

When I do this, the file gets printed like this

   DATA =
  [
    "{\"a\":78,\"b\":\"richardprice@kertzmann.info\"}"
  ]

which is not pretty :-(

Plus now, If I want to loop through the factorybot and generate 10 data and write it like this,

   DATA =
  [
      {
        a : 78
        b : test@test1.com
      },
      {
        a : 79
        b : test@test2.com
       },
       ...
    ]

How do I do this. TIA. Have been struggling on this for a while :-(

vendredi 26 juillet 2019

Duplicated link_to button - Rails 5

Hi have the next problem:

I have an iteration over a model called JobApplication which has_many with JobApplicationWorkExperiences, also it saves the information as nested form and with this is point everything is ok.

In my view I have the following iteration

<% @job_application.job_application_work_histories.each do |work| %>
 <% if work.completed?
  <% link_to 'Edit', goes_to_my_path %>
 <% end %>
<% end %>

The Edit button is being show as many time there is a JobApplicationWorkExperience with the JobApplication id, what should I do to avoid this problem?

Thanks for your help.

mercredi 24 juillet 2019

Namespace nested resources

I have the following routes on my project:

namespace :teacher do
 resources job_applications do
   resources :job_application_addresses
 end


My form has the folling code

<%= simple_form_for [:teacher, @job_application_address] do |form|

<% end %>


And my controller has the following:

def new
 @job_application_address = JobApplicationAddress.new
end

def create
 @job_application_address = JobApplicationAddress.new(job_application_address_params)
 @job_application_address.job_application = @job_application
   if @job_application_address.save
    flash[:success] = 'Successfully created'
   end
end


Finally I'm getting this error:

undefined method `teacher_job_application_addresses_path' for #<#<Class:0x00007fda0c4191d0>:0x00007fda143d1af8>
Did you mean?  teacher_job_application_path
               teacher_job_applications_path

Extracted source (around line #3):
<%= simple_form_for [:teacher, @job_application_address] do |form| %>

What should I do? I'll apprecciate your help.

mardi 23 juillet 2019

overiding policy.xml on docker

I was following the link https://help.heroku.com/RFDJQSG3/how-can-i-override-imagemagick-settings-in-a-policy-xml-file to override the default policy.xml of mini magic, but it is not happning.

Step taken by me.

  1. I created an .magic/policy.xml in my root_path
  2. In my environment i set the "MAGICK_CONFIGURE_PATH" => "/app/.magick/:/etc/ImageMagick-6/",

but still when i try identify -list policy

i still have result

Path: /etc/ImageMagick-6/policy.xml
  Policy: undefined
    rights: None 
  Policy: Coder
    rights: None 
    pattern: EPHEMERAL
  Policy: Coder
    rights: None 
    pattern: URL
  Policy: Coder
    rights: None 
    pattern: HTTPS
  Policy: Coder
    rights: None 
    pattern: MVG
  Policy: Coder
    rights: None 
    pattern: MSL
  Policy: Coder
    rights: None 
    pattern: TEXT
  Policy: Coder
    rights: None 
    pattern: SHOW
  Policy: Coder
    rights: None 
    pattern: WIN
  Policy: Coder
    rights: None 
    pattern: PLT
  Policy: Path
    rights: None 
    pattern: @*

Path: [built-in]
  Policy: Undefined
    rights: None 

It is not getting overrided.

lundi 22 juillet 2019

Rails request.referer didnt redirect to the previous url

I am trying to redirect the canceled page to the previous one when the item's been canceled but at the moment the codes below don't work - can you help?

def destroy
  order.cancel

  respond_to do |format|
    format.html { redirect_to request.referer.include? "cancel" ? request.referer : order_path(order.shopify_id), notice: 'Order cancelled successfully!' }
  end
end

def cancel
  shopify_order.cancel

  fulfilment_orders.each do |fo|
    fo.update!(state: :cancelled) unless fo.state.in?(%i[shipped delivered could_not_deliver])
  end
end

How to remove encryption from virtualbox through rails

I was troubleshooting a heroku problem with it not showing my google maps. I tried this code I found in this thread Ruby on Rails Google maps javascript api not working on heroku

I followed the directions and changed the production.rb file to config.assets.compile = true and ran the command RAILS_ENV=production rake assets:precompile

I received an error message from rails and I did what it said to correct the issue. Now my rails is encrypted and I cannot figure out how to unencrypt it. I have the master key just no place to type it. Because of this I cannot run my virtual box server. I get this error when I try [ENV]:/vagrant/src/nomster-engine $ rails server -b 0.0.0.0 -p 3000 => Booting Puma => Rails 5.2.3 application starting in development => Run rails server -h for more startup options Exiting Traceback (most recent call last): 80: from bin/rails:3:in <main>' 79: from bin/rails:3:inload' 78: from /vagrant/src/nomster-engine/bin/spring:15:in <top (required)>' 77: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:inrequire' 76: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in require' 75: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in' 74: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/spring-2.1.0/lib/spring/binstub.rb:11:in load' 73: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/spring-2.1.0/bin/spring:49:in' 72: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/spring-2.1.0/lib/spring/client.rb:30:in run' 71: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/spring-2.1.0/lib/spring/client/command.rb:7:incall' 70: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/spring-2.1.0/lib/spring/client/rails.rb:28:in call' 69: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/spring-2.1.0/lib/spring/client/rails.rb:28:inload' 68: from /vagrant/src/nomster-engine/bin/rails:9:in <top (required)>' 67: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:inrequire' 66: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:257:in load_dependency' 65: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:inblock in require' 64: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in require' 63: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:inrequire_with_bootsnap_lfi' 62: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in register' 61: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:inblock in require_with_bootsnap_lfi' 60: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in require' 59: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/commands.rb:18:in' 58: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/command.rb:46:in invoke' 57: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/command/base.rb:65:inperform' 56: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/thor-0.20.3/lib/thor.rb:387:in dispatch' 55: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/thor-0.20.3/lib/thor/invocation.rb:126:ininvoke_command' 54: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/thor-0.20.3/lib/thor/command.rb:27:in run' 53: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/commands/server/server_command.rb:142:inperform' 52: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/commands/server/server_command.rb:142:in tap' 51: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/commands/server/server_command.rb:147:inblock in perform' 50: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/commands/server/server_command.rb:51:in start' 49: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/commands/server/server_command.rb:89:inlog_to_stdout' 48: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/rack-2.0.7/lib/rack/server.rb:354:in wrapped_app' 47: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/commands/server/server_command.rb:27:inapp' 46: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/rack-2.0.7/lib/rack/server.rb:219:in app' 45: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/rack-2.0.7/lib/rack/server.rb:319:inbuild_app_and_options_from_config' 44: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/rack-2.0.7/lib/rack/builder.rb:40:in parse_file' 43: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/rack-2.0.7/lib/rack/builder.rb:49:innew_from_string' 42: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/rack-2.0.7/lib/rack/builder.rb:49:in eval' 41: from config.ru:in' 40: from config.ru:in new' 39: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/rack-2.0.7/lib/rack/builder.rb:55:ininitialize' 38: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/rack-2.0.7/lib/rack/builder.rb:55:in instance_eval' 37: from config.ru:3:inblock in ' 36: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:48:in require_relative' 35: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:inrequire' 34: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:257:in load_dependency' 33: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:inblock in require' 32: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:30:in require' 31: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:inrequire_with_bootsnap_lfi' 30: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in register' 29: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:inblock in require_with_bootsnap_lfi' 28: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/bootsnap-1.4.4/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in require' 27: from /vagrant/src/nomster-engine/config/environment.rb:5:in' 26: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/application.rb:361:in initialize!' 25: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/initializable.rb:60:inrun_initializers' 24: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/tsort.rb:205:in tsort_each' 23: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/tsort.rb:226:intsort_each' 22: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/tsort.rb:347:in each_strongly_connected_component' 21: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/tsort.rb:347:incall' 20: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/tsort.rb:347:in each' 19: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/tsort.rb:349:inblock in each_strongly_connected_component' 18: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/tsort.rb:431:in each_strongly_connected_component_from' 17: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/tsort.rb:350:inblock (2 levels) in each_strongly_connected_component' 16: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/2.5.0/tsort.rb:228:in block in tsort_each' 15: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/initializable.rb:61:inblock in run_initializers' 14: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/initializable.rb:32:in run' 13: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/railties-5.2.3/lib/rails/initializable.rb:32:ininstance_exec' 12: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/devise-4.6.2/lib/devise/rails.rb:37:in block in <class:Engine>' 11: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/devise-4.6.2/lib/devise/secret_key_finder.rb:10:infind' 10: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/devise-4.6.2/lib/devise/secret_key_finder.rb:24:in key_exists?' 9: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/core_ext/module/delegation.rb:271:inmethod_missing' 8: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/encrypted_configuration.rb:38:in options' 7: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/encrypted_configuration.rb:33:inconfig' 6: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/encrypted_configuration.rb:21:in read' 5: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/encrypted_file.rb:42:inread' 4: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/encrypted_file.rb:79:in decrypt' 3: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/messages/rotator.rb:21:indecrypt_and_verify' 2: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/message_encryptor.rb:157:in decrypt_and_verify' 1: from /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/message_encryptor.rb:183:in_decrypt' /home/vagrant/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/message_encryptor.rb:206:in `rescue in _decrypt': ActiveSupport::MessageEncryptor::InvalidMessage (ActiveSupport::MessageEncryptor::InvalidMessage)

I have searched Stack Overflow, used Google and read several articles but I am new to all this and taking a coding bootcamp so I don't fully understand what I am reading

Stock Data recommendations for cloning robin hood

I am currently trying to clone Robinhood for my full stack webapp dev project. And I was wondering if there's anyone out there that can give me a recommendation for a free API to use for stock and trading data to be used. And also a graphing library for Javascript that will be fitted for the project.

Please help! Thank you in advance!

I've been looking on Rapid API for some APIS such as Yahoo Finance, but because I'm a newbie I'm not sure what I need to look for exactly.

For graphs and charts I m considering Char.js

Redirect to the previous page(same page)with destroy method

I am creating a cancel order page where customers can click on the cancel button and the page will render "order canceled successfully" and stay on the cancel page with the button disabled. I've googled and searched through it still not too sure how to achieve that, please help thank you so much!

  def destroy

    order.cancel
    redirect_to order_path(order.shopify_id), notice: 'Order cancelled'


end

</div>
<%= link_to 'Cancel Here', order_path(@order.shopify_id), method: :delete, class: 'btn btn-danger ' %>


</div>


dimanche 21 juillet 2019

Mobility Gem translation, Take "en" default from stored json in database

i have used a mobility gem for translation and in database i am storing json like { "de": "Abc", "en": "Abc", "fr": "Abc" } so when i am passing "de" language to params then it is giving the Abc translated for de language but i wanna do that if language passed from params is not exist in above json then it should take "en" as default , so what can i do for that?

in model i have used below code:

  include LocaleExtension
  extend Mobility
  translates :restaurant_name, type: :string
  # and  i have stored above json in restaurant_name field in database.

samedi 20 juillet 2019

What's the meaning of :[]

I'm new to ruby on rails, there's a code something like:

personMap.try(:[], :name)

What's the meanning of :[] here?

jeudi 18 juillet 2019

How to use Basic128 (encryption/encoding) in my signature?

I am calling soap API's with X.509 certificate.

And receiving an error that i have to use Basic128 in the signature.

Here is my Signature:

def the_signature
        raise MissingCertificate, "Expected a private_key for signing" unless certs.private_key
        signed_info = at_xpath(@document, "//Envelope/Header/Security/Signature/SignedInfo")
        signed_info = signed_info ? canonicalize(signed_info) : ""
        signature = certs.private_key.sign(OpenSSL::Digest::SHA1.new, signed_info)
        Base64.encode64(signature).gsub("\n", '') 
end


How can i use Basic128 to solve the above problem?

Couldn't find Order in ruby on rails

I am trying to build a page to load order id but it threw back Couldn't find Order, can you help?

routes.rb get '/orders/cancellation', to: 'orders#cancel'

<h1>Preview & Cancel your order here</h1>
<div class="block">

  <h1> Order <%= @order.name %></h1>

  <div id="multiple-file-preview">
    <ul id="sortable">
      <div class="clear-both"></div>
    </ul>
  </div>
</div>

def cancel
    paginate_versions PaperTrail::Version.where(order_id: order.id).order(created_at: :desc)
    remote_versions_pagination
  end

def order
    @order ||= Order.find_by!(shopify_id: params[:id])
  end

mercredi 17 juillet 2019

validation failed in polymorphic association

When I do a migration I get the following error "ActiveRecord::RecordInvalid: Validation failed: Huntinganimals must exist"

I'm not sure where I would declare "huntinganimals".

class Picture < ApplicationRecord
  belongs_to :camera_model
  has_one :animals, :as =>:HuntingAnimals
end
class User < ApplicationRecord
    has_one :animals, :as =>:HuntingAnimals
end
class Animal < ApplicationRecord
  belongs_to :HuntingAnimals, :polymorphic => true
end


class CreateAnimals < ActiveRecord::Migration[5.2]
  def change
        create_table :animals do |t|
        t.references :HuntingAnimals, polymorphic: true
    end
  end
end

get record from many to many relationship

I am working on an old rails project. I have a many-to-many relationship between Student and Course via a bridge model named students_courses.

Student class:

class Student < ActiveRecord::Base
  has_and_belongs_to_many :courses, :class_name => 'Course', :join_table => 'students_courses'
end

Course class:

class Course < ActiveRecord::Base

end

StudentCourse class:

class StudentCourse < ActiveRecord::Base
  belongs_to :student
  belongs_to :course
end

There is a firstname attribute in Student model. I would like to find the student who has firstname "John" and studying course "foo". How can I get this in ruby of Rails?

mardi 16 juillet 2019

Surrogate character( 𩸽𠮟) from ruby on rails application gets saved to oracle database in question mark format (?)

Surrogate character( 𩸽𠮟) from ruby on rails application gets saved to oracle database in question mark format (?)

Ruby -2.4.1 Rails - 5.0 Oracle - 11.2

Using above configurations

firing below query

UPDATE table_name SET my_message = N'テストトト VP-𩸽𠮟' WHERE table_name.MERCHANT_ID = 'merchant4'  

While updating above record it gets saved to db as 'テストトト VP-??'

Please suggest.

Thank you in advance.

lundi 15 juillet 2019

content_tag populate drop-down with unknow "black squre" in front

I used the following code (in .slim file) to generate a dropdown. Each item in the dropdown is a hyperlink to other website. But I could not find out where does the black square ahead of each item is coming from. How to remove it?

enter image description here

li.dropdown
     a.dropdown-toggle data-toggle="dropdown" href="#"
         | Other 
         span.caret
     ul.dropdown-menu role="menu" 
        == content_tag :ul do items.map do |item| concat(content_tag(:li) do link_to(item, "#") end) end end

Minimagick error during upload "composite -compose Over -gravity North"

I am trying to upload an image by gem "carrierwave", "~> 1.1.0" and gem "mini_magick", "~> 4.7.0" to upload image. I am getting this error.

I am using this code to upload image.

  MiniMagick::Tool::Convert.new do |i|
    i.size "#{image_width.ceil}x#{watermarked_image_height.ceil}"
    i.gravity "center"
    i.xc "white"
    i << temp_image_path
  end
  @_watermarked_image = MiniMagick::Image.open(temp_image_path)
  @_watermarked_image = @_watermarked_image.composite(source_image, "jpg") do |c|
    c.compose "Over"
    c.gravity "North"
  end

:ERROR

composite -compose Over -gravity North /tmp/mini_magick20190710-1-g0dcpy /tmp/mini_magick20190710-1-1fil3d9.jpg /tmp/mini_magick20190710-1-ibbwos.jpg` failed with error:\\n

vendredi 12 juillet 2019

Faraday post request with Rails form

I am trying to make a post request from my controller to a third party website using faraday but I can't get it to work?

I have a method in my homes controller to make the request, a route setup for the method and a form for my request but I can't get the request to be successful no idea what i am doing wrong


    #homes_controller.rb
    def alpaca
        @conn = Faraday.post('https://paper-api.alpaca.markets/v2/orders') do |req|
          req.headers['APCA-API-KEY-ID'] = 'key'
          req.headers['APCA-API-SECRET-KEY'] = 'secret'
          req.body = "{'symbol': '#{params[:ticker]}'}"
          req.body = "{'qty': '#{params[:qty]}'}"
          req.body = "{'side': '#{params[:side]}'}"
          req.body = "{'type': '#{params[:ticker]}'}"
          req.body = "{'time_in_force': '#{params[:time_in_force]}'}"
        end
        redirect_to homes_path
      end

    #routes.rb
     resources :homes
      root 'homes#index'
      post '/alpaca', to: 'homes#alpaca'

    #homes/index.html.rb
     <%=form_tag alpaca_path do %>
     <%=label_tag "Ticker"%>
     <%=text_field_tag :ticker %>
     <%=label_tag "qty"%>
     <%=number_field_tag :qty %>
     <%=label_tag "side"%>
     <%=text_field_tag :side %>
     <%=label_tag "type"%>
     <%=text_field_tag :type %>
     <%=label_tag "time_in_force"%>
     <%=text_field_tag :time_in_force %>
     <%=submit_tag%>
     <%end%>


I am trying to get this form to post the params passed in sent to alpaca's trading api

how to fix undefined method 'each ' for nil:class

I need some help about this error.i check evrything such mi index,and my controller but i still get the same error :NoMethodError in Articles#index undefined method 'each' for nil;class

<% @articles.each do | article | %>

  <td><%= article.title %></td>

Generate uuid in size of 16 and datatype : binary

To generate uuid for 16bit binary datatype in rails

I have used this 'SecureRandom.uuid' but it takes very big size. It takes big size, and i have binary(16) datatype and size, database=mysql; uuid = SecureRandom.uuid

I want 16 sized uuid and store in binary datatype.

jeudi 11 juillet 2019

How to seperate Admin and User database in Rails

I have devise gem in my application. I've been playing around with making some tables etc. Now I want to separate the database for the admin and the database for the user. I know its one single database. But, I'm not sure how to get it going in Rails.

mercredi 10 juillet 2019

Selenium::WebDriver::Error::UnknownError: invalid argument: can't kill an exited process | Travis webdrivers

I try to build on Travis and launch my user test but I have the following error : Selenium::WebDriver::Error::UnknownError:invalid argument: can't kill an exited process I may use wrong version of firefox and geckodriver but can't figure out what is the right one.. Here is the screenshot of travis interface and my travis.yml file. Thanks a lot !

language: ruby
cache:
  bundler: true
  yarn: true
  directories:
  - vendor/bundle
  - node_modules
  - tmp/cache
  - public/assets
services:
  - redis-server
sudo: required
addons:
  postgresql: '9.5'
  chrome: stable
  firefox: latest
  apt:
    packages:
      - chromium-chromedriver
      - google-chrome-stable

before_install:
  - gem install bundler -v 2.0.1
  - openssl aes-256-cbc -K $encrypted_67af5a301080_key -iv $encrypted_67af5a301080_iv
    -in application.yml.enc -out config/application.yml -d
  - sudo apt-get update
  - sudo apt-get install google-chrome-stable
  - wget https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-linux64.tar.gz
  - mkdir geckodriver
  - tar -xzf geckodriver-v0.24.0-linux64.tar.gz -C geckodriver
before_script:
  - psql -c 'create database simundia_v6_test;' -U postgres
script:
  - bundle exec rake db:migrate
  - yarn install --production=false
  - bundle exec rails assets:precompile
  - bundle exec rspec $TESTFOLDER
env:
  - TESTFOLDER=spec/features/coach_journey_spec.rb
  - TESTFOLDER=spec/features/coached_journey_spec.rb
  - TESTFOLDER=spec/features/client_demo_journey_spec.rb
  - MOZ_HEADLESS=1

10.87s$ bundle exec rspec $TESTFOLDER
Capybara starting Puma...
* Version 3.12.0 , codename: Llamas in Pajamas
* Min threads: 0, max threads: 4
* Listening on tcp://127.0.0.1:43817
F
Failures:
  1) Coach user journey success
     Failure/Error: visit '/users/sign_in'
     Selenium::WebDriver::Error::UnknownError:
       invalid argument: can't kill an exited process
     # ./spec/features/utilities.rb:18:in `visit_session_new'
     # ./spec/features/coach_journey_spec.rb:17:in `block (2 levels) in <top (required)>'

How do I retrieve a random GET request in Ruby on Rails 5?

I've created my REST API based on Michael Scott from the Office, so far if you go onto the main part of the API it displays all the quotes /api/v1/quotes/ and you can get individual ones if you add an id number such as /api/v1/quotes/5,but I want users to be able to get a random quote when they put in a GET request.

This would preferably be done with an extra part of the URL such as /api/v1/quotes/random.

I've looked at a lot online but I can't figure this out. Do I put my code into the quotes controller and create another function or do I have to put this somewhere else such as routes.db? Also do I put in the SQL function of RANDOM or is there a better and more efficient way to randomise it. My database only has 50 records in it and it's done in mysql2.

Thanks in advance.

It's my first time posting here as usually I hate asking for help as I think I can always figure it out myself but I'm extremely new to Ruby so I'm fairly clueless on how to solve this. If you need me to clarify my question then just let me know.

Ruby Rails equivalent in nodejs

I'm new in NodeJS I wanted to do the equivalent of this code which is coded in Ruby Rails.It is a survey that I must implement with my frontend

class SurveysController < ApplicationController
  before_action :authorize, only: [:create, :update, :destroy, :index]
  before_action :set_user, only: [:create, :destroy, :index]
  before_action :set_survey, only: [:show, :update, :destroy]

  # GET /surveys
  def index
    @surveys = @user.surveys

    render json: @surveys
  end

  # GET /surveys/1
  def show
    render json: @survey
  end

  # POST /surveys
  def create
    @survey = Survey.new(
      title: survey_params[:title],
      sub_title: survey_params[:sub_title],
      questions: survey_params[:questions].to_json,
      user: @user
    )

mardi 9 juillet 2019

Initialization error expecting one amount seeing another

I'm trying to complete the card shuffle assignment and must use initialize and self in the code. I have defined what rank and suit mean but the program does not recognize that the variables are used, which they are. Then in the initialization, it says I have the wrong number of arguments

I tried changing the name of the items in the initialize code. I split @cards << (self.rank, self.suit) into 2 lines but made no difference. I moved the variable definitions inside the initialize code which helped with some messages but not the all.

This is the whole program

class Card
  attr_accessor :rank, :suit
  rank = [2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace"]
  suit = ["Hearts", "Diamond", "Clubs", "Spades"]

  def initialize(rank, suit)

    self.rank = rank
    self.suit = suit

  end

  def output_card
    puts "#{self.rank} of #{self.suit}"
  end

  #def self.random_card
   # Card.new(rand(rank, suit))
  #end
end

class Deck
  attr_accessor :rank, :suit

  #Generates the 4 suits of cards in each denomination
  def initialize(cards)
    cards = Card.new("rank", "suit")
    @cards = []
    @cards << Card.new(self.rank, self.suit)

  end

  #shuffles the deck of cards
  def shuffle
    unless @cards.empty?
      @cards.shuffle!
    end
  end


  #def self.top_card
    #Card.new(self.rank, self.suit)
  #end

  #Deals the cards from the top of the virtual deck.
  def deal
    @cards.each do |card|
      card.output
    end
  end  
end

deck = Card.new
deck.shuffle
deck.deal

This is the current error message I get.

Shannons-MacBook-Air:Desktop leighrachal$ Ruby -w Card.rb
Card.rb:3: warning: assigned but unused variable - rank
Card.rb:4: warning: assigned but unused variable - suit
Card.rb:6:in `initialize': wrong number of arguments (given 0, expected 2) (ArgumentError)
    from Card.rb:53:in `new'
    from Card.rb:53:in `<main>'

Can stand-alone Rails server accept requests on multiple IP addresses

I want to know if I can launch a Rails server (Puma or otherwise) with options that will allow it to be hit over any IP address (127.0.0.1, localhost, network IP address, etc).

I think -b option only takes one IP address (not a wildcard or anything), and I have to restart it changing that option to allow connections over various IP addresses.

rails s -b 127.0.0.1 -p 3000

I would like to hit my server via both a browser on my machine and a browser on my iPhone on my network, and possibly a browser in a VM on my machine.

lundi 8 juillet 2019

How to use rails update method for multiple object with collection

I am trying to update multiple objects with rails update method with update collection object as following codes:(couldn't really find the collection method)

def update

      @reiew = Review.find(reivew_params)
       review.update!(reivew_params)

        if @reivews.update(reivew_params)
        respond_to do |format|
        format.html { redirect_to reivew_path}
      end
    else
        respond_to do |format|
        format.html { notice: 'saved errors'}
      end
    end
  end

samedi 6 juillet 2019

Deploy rails app to Heroku Error ArgumentError: Invalid option: harmony

I finished my blog and I'm trying to deploy it to heroku, but I keep getting this error.

I've tried changing my production.rb, Gemfile, and application.js which was advised from other people with the same problems, but none of it worked. Here's what I've done

I changed my production.rb to this

        config.assets.js_compressor = Uglifier.new(harmony: true)

Application.js:


        //= require jquery
        //= require jquery_ujs
        //= require turbolinks
        //= require ckeditor/init
        //= require_tree .

I've changed jquery_ujs to rails_ujs and it didn't change anything

Gemfile


ruby '2.5.1'

group :production do
  gem 'pg'
  gem 'rails_12factor'
end

group :development do
  gem 'sqlite3', '~> 1.3.6'
end

gem 'rails', '~> 5.2.1'
gem 'puma', '~> 3.11'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.0.3', require: 'uglifier'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'bootsnap', '>= 1.1.0', require: false
gem 'redcarpet', '~> 3.4'
gem 'pygments.rb', '~> 1.2', '>= 1.2.1'
gem 'friendly_id', '~> 5.2', '>= 5.2.4'
gem 'will_paginate', '~> 3.1', '>= 3.1.6'
gem 'mail_form', '~> 1.5', '>= 1.5.1'
gem 'devise', '~> 4.2'
gem "paperclip", "~> 6.0.0"
gem 'ckeditor', '~> 4.1'
gem 'meta-tags', '~> 2.1'
gem 'rb-readline', '~> 0.5.3'
gem 'cancancan'
gem 'carrierwave'
gem 'mini_magick'
gem 'social-share-button'





group :development, :test do
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end
group :test do
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  gem 'chromedriver-helper'
end
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]


Here is my terminal

remote:        Running: rake assets:precompile
remote:        rake aborted!
remote:        ArgumentError: Invalid option: harmony
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/uglifier-2.7.2/lib/uglifier.rb:168:in `block in initialize'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/uglifier-2.7.2/lib/uglifier.rb:167:in `each'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/uglifier-2.7.2/lib/uglifier.rb:167:in `initialize'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/config/environments/production.rb:26:in `new'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/config/environments/production.rb:26:in `block in <main>'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/railtie.rb:216:in `instance_eval'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/railtie.rb:216:in `configure'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/config/environments/production.rb:1:in `<main>'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:287:in `block in require'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:253:in `load_dependency'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:287:in `require'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/engine.rb:602:in `block (2 levels) in <class:Engine>'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/engine.rb:601:in `each'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/engine.rb:601:in `block in <class:Engine>'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/initializable.rb:32:in `instance_exec'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/initializable.rb:32:in `run'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/initializable.rb:61:in `block in run_initializers'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/initializable.rb:50:in `each'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/initializable.rb:50:in `tsort_each_child'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/initializable.rb:60:in `run_initializers'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/application.rb:361:in `initialize!'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/config/environment.rb:5:in `<main>'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:65:in `register'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/bootsnap-1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:287:in `block in require'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:253:in `load_dependency'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:287:in `require'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/application.rb:337:in `require_environment!'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/railties-5.2.1/lib/rails/application.rb:520:in `block in run_tasks_blocks'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/sprockets-rails-3.2.1/lib/sprockets/rails/task.rb:62:in `block (2 levels) in define'
remote:        /tmp/build_08823881a010f97ecfcad2f83b760e2b/vendor/bundle/ruby/2.5.0/gems/rake-12.3.1/exe/rake:27:in `<top (required)>'
remote:        Tasks: TOP => environment
remote:        (See full trace by running task with --trace)
remote: 
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
remote: 
remote:  !     Push failed
remote: Verifying deploy...
remote: 
remote: !   Push rejected to obscure-harbor-21335.

Any help would be appreciated thank you

How to convert return string from webservice to pdf file

I need to convert string which i am getting from webservice to pdf. Basically webservice is to download file, but i want to use it like download and save file to my database from backend.

Concern is sample pdf file returns is in string format like below

"%PDF-1.3\r\n%\xE2\xE3\xCF\xD3\r\n\r\n1 0 obj\r\n<<\r\n/Type /Catalog\r\n/Outlines 2 0 R\r\n/Pages 3 0 R\r\n>>\r\nendobj\r\n\r\n2 0 obj\r\n<<\r\n/Type /Outlines\r\n/Count 0\r\n>>\r\nendobj\r\n\r\n3 0 obj\r\n<<\r\n/Type /Pages\r\n/Count 2\r\n/Kids [ 4 0 R 6 0 R ] \r\n>>\r\nendobj\r\n\r\n4 0 obj\r\n<<\r\n/Type /Page\r\n/Parent 3 0 R\r\n/Resources <<\r\n/Font <<\r\n/F1 9 0 R \r\n>>\r\n/ProcSet 8 0 R\r\n>>\r\n/MediaBox [0 0 612.0000 792.0000]\r\n/Contents 5 0 R\r\n>>\r\nendobj\r\n\r\n5 0 obj\r\n<< /Length 1074 >>\r\nstream\r\n2 J\r\nBT\r\n0 0 0 rg\r\n/F1 0027 Tf\r\n57.3750 722.2800 Td\r\n( A Simple PDF File ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 688.6080 Td\r\n( This is a small demonstration .pdf file - ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 664.7040 Td\r\n( just for use in the Virtual Mechanics tutorials. More text. And more ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 652.7520 Td\r\n( text. And more text. And more text. And more text. ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 628.8480 Td\r\n( And more text. And more text. And more text. And more text. And more ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 616.8960 Td\r\n( text. And more text. Boring, zzzzz. And more text. And more text. And ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 604.9440 Td\r\n( more text. And more text. And more text. And more text. And more text. ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 592.9920 Td\r\n( And more text. And more text. ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 569.0880 Td\r\n( And more text. And more text. And more text. And more text. And more ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 557.1360 Td\r\n( text. And more text. And more text. Even more. Continued on page 2 ...) Tj\r\nET\r\nendstream\r\nendobj\r\n\r\n6 0 obj\r\n<<\r\n/Type /Page\r\n/Parent 3 0 R\r\n/Resources <<\r\n/Font <<\r\n/F1 9 0 R \r\n>>\r\n/ProcSet 8 0 R\r\n>>\r\n/MediaBox [0 0 612.0000 792.0000]\r\n/Contents 7 0 R\r\n>>\r\nendobj\r\n\r\n7 0 obj\r\n<< /Length 676 >>\r\nstream\r\n2 J\r\nBT\r\n0 0 0 rg\r\n/F1 0027 Tf\r\n57.3750 722.2800 Td\r\n( Simple PDF File 2 ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 688.6080 Td\r\n( ...continued from page 1. Yet more text. And more text. And more text. ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 676.6560 Td\r\n( And more text. And more text. And more text. And more text. And more ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 664.7040 Td\r\n( text. Oh, how boring typing this stuff. But not as boring as watching ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 652.7520 Td\r\n( paint dry. And more text. And more text. And more text. And more text. ) Tj\r\nET\r\nBT\r\n/F1 0010 Tf\r\n69.2500 640.8000 Td\r\n( Boring.  More, a little more text. The end, and just as well. ) Tj\r\nET\r\nendstream\r\nendobj\r\n\r\n8 0 obj\r\n[/PDF /Text]\r\nendobj\r\n\r\n9 0 obj\r\n<<\r\n/Type /Font\r\n/Subtype /Type1\r\n/Name /F1\r\n/BaseFont /Helvetica\r\n/Encoding /WinAnsiEncoding\r\n>>\r\nendobj\r\n\r\n10 0 obj\r\n<<\r\n/Creator (Rave \\(http://www.nevrona.com/rave\\))\r\n/Producer (Nevrona Designs)\r\n/CreationDate (D:20060301072826)\r\n>>\r\nendobj ... 

Please suggest.

mercredi 3 juillet 2019

Override column_names for Model Class

I am customizing my Active admin with below code

ActiveAdmin.register Question do
  index do
    Question.column_names.each do |c|
      column c.to_sym
    end
  end
end

However, I don't want to show created_at and updated_at fields. How can I override this method for all of my Model Class to hide those two fields?

mardi 2 juillet 2019

How to write ActiveJob log into a different file

I want to find a way to log ActiveJob logs to a different log other than the production.log

I am on a rails 4.2.5 project. The project used a lot of ActiveJob and DelayedJob. they write into same log, making the log very messy and hard to debug. I want to write the job log to a different file, so I did this in initializers/delayed_job.rb:

delayed_job_logger = Logger.new(File.join(Rails.root, 'log', "delayed_job_# {Rails.env}.log"), 10, 100 * 1024 * 1024)
Delayed::Worker.logger = delayed_job_logger
ActiveJob::Base.logger = delayed_job_logger

After the configuration, the delayed job logs is doing well. it did write to delayed_job_production.log

I, [2019-07-02T12:33:36.664242 #14335] INFO -- : 2019-07-02T12:33:36-0500: [Worker(delayed_job.6 host:pioneer3-app-production pid:14335)] Job ActiveJob::QueueAdapters::DelayedJobAdapter::JobWrapper (id=60672406) (queue=TfrToP2InTimeJob) COMPLETED after 0.0098

but the ActiveJob log is still mixing in the production.log

I, [2019-07-02T12:33:42.091068 #13730] INFO -- : [ActiveJob] [PipelineRollMonthJob] [93fc7600-2ba9-48eb-a6bd-729d3e830114] Performed PipelineRollMonthJob from DelayedJob(PipelineRollMonthJob) in 5.53ms

how can I fix the activejob log?

lundi 1 juillet 2019

joins on tables without relation in rails

What's the work around of not being able to use joins on tables that don't have relation?

E.g:

class Student
end

class Lesson
end


There is no explicit correlation between Student and Lesson, however, in DB, we have implicit correlation: students.lesson_id and lessons.id.

Using pure SQL can join these two tables, however, using joins provided by rails like this:

Student.joins(:lesson).where('student.lesson_id=lesson.id')

will throw "Association named 'lesson' was not found on Student; perhaps you misspelled it?"

I'm looking for work around with below requirements:

  • In order to improve the efficiency, using RDBMS queries will be ideal. (Rails sort_by, find etc are not)
  • In order to improve readability, raw SQL is not ideal.

Is there any work around out there? Thanks!

how to disable checkbox on condition?

I am trying to create a spreadsheet on index page to display items with checkbox and if validated - the checkbox will be disabled so that people won't mis-ticked it. can you help?

In app/views/scooties_coupons/index.html.erb

<table class="table table-hover">

<h1>Scooties Coupons</h1>

<%= form_with(url: validate_coupons_path, method: 'patch') do |f| %>
  <table>
    <thead>
      <tr>
        <th>Valid</th>
        <th>Coupon</th>
        <th>Redeemed</th>
        <th>First name</th>
        <th>Surname</th>
        <th>email</th>
        <th>occupation</th>
        <th>validation</th>
        <th colspan="3"></th>
      </tr>
    </thead>

    <tbody>
      <% @scooties_coupons.each do |scooties_coupon| %>
        <tr>
          <td>
            <%= fields_for('scooties_coupons[]', scooties_coupon) do |cf|
              cf.check_box(:validated)
            end %>
          </td>
          <td><%= scooties_coupon.coupon %></td>
          <td><%= scooties_coupon.redeemed %></td>
          <td><%= scooties_coupon.first_name %></td>
          <td><%= scooties_coupon.surname %></td>
          <td><%= scooties_coupon.email %></td>
          <td><%= scooties_coupon.occupation %></td>

        </tr>
      <% end %>
    </tbody>
  </table>
  <%= f.submit %>
<% end %>

<br>

</table>


in app/controllers/scotties_coupons_controller.rb:


def set_valid_coupons
  to_valid = params[:scooties_coupons].select do |id, attrs|
    attrs[:validated] == '1'
  end
  to_not_valid = params[:scooties_coupons].reject do |id, attrs|
    attrs[:validated] == '1'
  end
  ScootiesCoupon.transaction do
    ScootiesCoupon.where(id: to_valid.keys, validated: false).update_all(
      validated:true)
    ScootiesCoupon.where(id: to_not_valid.keys, validated: true).update_all(
      validated:false)
  end
  redirect_to action: :index, notice: 'Validations updated'
end


How do I customize a view generated by a Comfy CMS Page?

In my Rails 3.2 app, I am using comfortable_mexican_sofa 1.8.

I have created some 'CMS Pages' within the CMS admin (some static pages like 'About Us', 'Contact Us', etc.). All of these pages are populated by the fields within the CMS Admin section.

But I can't figure out how to customize the template so that it renders the about us correctly.

Here is the log:

Started GET "/about" for 127.0.0.1 at 2019-07-01 01:42:05 -0500
Processing by CmsContentController#render_html as HTML
  Parameters: {"cms_path"=>"about"}
   (1.3ms)  SELECT COUNT(*) FROM "admins" WHERE (admins.superadmin = 't')
   (0.7ms)  SELECT COUNT(*) FROM "cms_sites" 
  Cms::Site Load (0.4ms)  SELECT "cms_sites".* FROM "cms_sites" LIMIT 1
  Cms::Page Load (1.5ms)  SELECT "cms_pages".* FROM "cms_pages" WHERE "cms_pages"."site_id" = 1 AND "cms_pages"."is_published" = 't' AND "cms_pages"."full_path" = '/about' ORDER BY cms_pages.position LIMIT 1
  Cms::Layout Load (0.8ms)  SELECT "cms_layouts".* FROM "cms_layouts" WHERE "cms_layouts"."id" = 5 ORDER BY cms_layouts.position LIMIT 1
  Cms::Block Load (1.0ms)  SELECT "cms_blocks".* FROM "cms_blocks" WHERE "cms_blocks"."page_id" = 9 AND "cms_blocks"."identifier" = 'blurb' LIMIT 1
  Cms::Page Load (0.8ms)  SELECT "cms_pages".* FROM "cms_pages" WHERE "cms_pages"."id" = 9 ORDER BY cms_pages.position LIMIT 1
  CACHE (0.0ms)  SELECT "cms_layouts".* FROM "cms_layouts" WHERE "cms_layouts"."id" = 5 ORDER BY cms_layouts.position LIMIT 1
  Cms::Layout Load (0.8ms)  SELECT "cms_layouts".* FROM "cms_layouts" WHERE "cms_layouts"."id" = 2 ORDER BY cms_layouts.position LIMIT 1
  Cms::Block Load (1.3ms)  SELECT "cms_blocks".* FROM "cms_blocks" WHERE "cms_blocks"."page_id" = 9
  Rendered inline template (1.5ms)
  Rendered partials/cms/pages/_header.html.haml (78.3ms)
  Cms::Page Load (0.7ms)  SELECT "cms_pages".* FROM "cms_pages" WHERE "cms_pages"."id" = 1 ORDER BY cms_pages.position LIMIT 1
  Rendered inline template within layouts/cms_inside (108.3ms)
  Cms::Page Load (1.3ms)  SELECT "cms_pages".* FROM "cms_pages" WHERE "cms_pages"."site_id" = 1 AND (parent_id IS NULL) ORDER BY cms_pages.position LIMIT 1
  Cms::Page Load (0.7ms)  SELECT "cms_pages".* FROM "cms_pages" WHERE "cms_pages"."parent_id" = 1 AND "cms_pages"."is_published" = 't' ORDER BY cms_pages.position OFFSET 1
  Rendered shared/_navbar.html.erb (13.5ms)
  Cms::Snippet Load (1.2ms)  SELECT "cms_snippets".* FROM "cms_snippets" WHERE "cms_snippets"."site_id" = 1 AND "cms_snippets"."identifier" = 'footer_contact' ORDER BY cms_snippets.position LIMIT 1
  Rendered inline template (1.5ms)
  Rendered shared/_footer.html.erb (13.6ms)
Completed 200 OK in 386.2ms (Views: 324.8ms | ActiveRecord: 12.5ms)

I don't have an 'about' path declared in my routes.rb, nor an about_controller and therefore I don't have a app/views/cms/pages/about.html.erb or anything like that.

I do have things like layouts/cms_inside which renders correctly, but it has a yield block that just renders the data collected from the text fields in the CMS Admin.

I have checked the documents at the GH repo, but it isn't clear about how to customize these generated pages.

Thoughts?