samedi 31 août 2019

How to validate emails with error messages

I am trying to validate the format of users email.

I have tried this

<% if @user.errors.any? %>
<h2> Error! Invalid password or Email </h2>
<ul>
<% @users.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %> 

I experimented with this from a old ruby video but it didnt seen to pan out. this is my user.rb model

class User < ApplicationRecord
        has_secure_password
        validates :email, presence: true, uniqueness: true
        validates :password, length: { minimum: 4 }
        validates :email, format: { with: /(\A([a-z]*\s*)*\<*([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\>*\Z)/i }
end

I get this error currently

No route matches {:action=>"show", :controller=>"users", :id=>nil}, missing required keys: [:id] undefined method `errors' for nil:NilClass whenever the password or email makes an error from the requirements.

vendredi 30 août 2019

devise_for and devise_scope do not bypass authentication

I'm using rails 3.2.21 and currently upgrading to devise 3.5.10 (from 1.5.4). I have a number of routes defined in a devise_scope :user block.

Here's a sample route; the same thing is happening with other routes in my devise_scope and devise_for blocks:

devise_scope :user do
    get 'register/:purchase_url_path', :controller => :purchases, :action => :new_order, as: :ecommerce, :constraints => { :purchase_url_path => /[\w\.$-@!^]+/ }
end

When I make a request to a page defined by one of these routes, I am redirected to the sign_in page.

I've figured out that the reason for this is in the authenticate_user! method, where

devise_controller?

returns false. Before the upgrade this method was returning true.

Before the devise upgrade, executing 'PurchasesController.ancestors' in irb returns a list including:

Devise::Controllers::InternalHelpers,
Devise::Controllers::ScopedViews,
Devise::Controllers::SharedHelpers,

After the upgrade those items are not present.

What have I done wrong?

lundi 26 août 2019

Rails 3.2.x: how to filter long parameters from getting logged using ActionController action?

There are similar questions like this, this, and this.

None help because the goal is to prevent logging of long parameters within a specific action instead of using config.filter_parameters. Also the answer must work for Rails 3.2.x while many answers are based on Rails 5.

One answer suggests calling request.filtered_parameters inside the controller method, but calling request.filtered_parameters.delete :long_param did not stop :log_param from getting logged.

jeudi 22 août 2019

Scope of POROs in Rails

It seems like when using only class methods on a PORO like a Service in a Rails app and called by controllers, that there is only one instance of the Service object created across all requests.

I know Rails creates new instances of Controllers and Models per request, but haven't seen anything documented about how Rails treats your own POROs.

What's your understanding?

mercredi 21 août 2019

Extracting image index from array in order to insert image into a bootstrap carousel

I have an array of images which I can iterate over and display on my page however this is not what I want. I would like to find the index of each image in my array so that (on each loop) I can insert one of the images into my bootstrap carousel slides.

Will I need Javascript to do this? I am unsure and hope someone can point me in the right direction.

To start I tried to do a for each with index loop and extract the index but I was not able to :(

This is the bootstrap carousel. So far you can see that I have put my iteration into the first slide which means all 3 images are showing on the first slide:

<div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
     <!--  <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(88).jpg"
       alt="First slide"> -->
      <!-- app/views/posts/show.html.erb -->
     <% if @service.images.attached? %>
      <% @service.images.each do |image| %>
        <%= image_tag(image) %>
        <% end %>
     <% end %>
    </div>
     <div class="carousesl-item">
   <!--   <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(121).jpg"
    alt="Second slide"> -->
    </div>
    <div class="carousel-item">
   <!--    <img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(31).jpg"
     alt="Third slide"> -->
    </div>
  </div>
  <!--/.Slides-->
  <!--Controls-->
  <a class="carousel-control-prev" href="#carousel-thumb" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carousel-thumb" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
  <!--/.Controls-->
  <ol class="carousel-indicators">
    <li data-target="#carousel-thumb" data-slide-to="0" class="active">
      <img src="https://mdbootstrap.com/img/Photos/Others/Carousel-thumbs/img%20(88).jpg" width="100">
    </li>
    <li data-target="#carousel-thumb" data-slide-to="1">
      <img src="https://mdbootstrap.com/img/Photos/Others/Carousel-thumbs/img%20(121).jpg" width="100">
    </li>
    <li data-target="#carousel-thumb" data-slide-to="2">
      <img src="https://mdbootstrap.com/img/Photos/Others/Carousel-thumbs/img%20(31).jpg" width="100">
    </li>
  </ol>
</div>
<!--/.Carousel Wrapper-->
</div>

mardi 20 août 2019

How to fix 'Please run rails webpacker: install Error: No such file or directory @ rb_sysopen"?

I am attempting to create my first Ruby on Rails application following the documentation outlined on the website. When I attempted to run the server with 'rails server' from the cmd line I receive this error...

C:/Ruby/rubyinstaller-2.5.5-1-x64/rubyinstaller-2.5.5-1-x64/lib/ruby/gems/2.5.0/gems/webpacker-4.0.7/lib/webpacker/configuration.rb:91:in `rescue in load': Webpacker configuration file not found C:/Users/{username}/Desktop/Projects/Ruby on Rails/Blog Application/blog/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - C:/Users/{username}/Desktop/Projects/Ruby on Rails/Blog Application/blog/config/webpacker.yml

OS: Windows 10
Yarn version: 1.17.3
Node.js version - v10.15.3
Rails version - 6.0.0
Ruby version - Ruby 2.5.5p157 (2019-03-15 revision 67260) [x64-mingw32]
sqlite3 version - 3.22.0

I expect for the server to run successfully and to open localhost:3000 to Yay! You're on rails

sort ruby hash by specific key

I have a ruby hash like this

 {"id"=>62, "name"=>"Wine and Spirits"}
 {"id"=>63, "name"=>"Tobacco"}
 {"id"=>64, "name"=>"Printing"}
 {"id"=>65, "name"=>"Information Services"}
 {"id"=>66, "name"=>"Business Supplies and Equipment"}

How do I sort this by name? I tried

 categories.sort_by {|_key, value, _key1, value1| value1}

But that did not work

Ruby : How to add a specific line from a document.txt to a comment field with specific id and then move to next line?

How can i add a specific line from my document.txt to youtube comment field with specific id and then move to next line on my document.txt . The id of youtube comment field is 'contenteditable-root' . I have created this code but the text that is been added on the youtube comment field show in brackets for example ["Hello"]

Or in second example it shows nothing

Example 1:

file = 'comments.txt'
File.readlines(file).each do |i|
            files = [i]
            files.each { |val| 

browser.execute_script("document.getElementById('contenteditable-root').innerHTML = '#{files}';")

}
end

Example 2:

line_number = 1 
loop do
comments = IO.readlines('comments.txt')[line_number-1]
browser.execute_script("document.getElementById('contenteditable-root').innerHTML = '#{comments}';")
line_number += 1 
end

lundi 19 août 2019

Image not showing for multiple image upload with active storage

I have followed a tutorial on how to upload multiple images using active record. I have installed active record, added my associations to my model and when I create a Service (my model) everything seems to be working when I upload 3 images i.e no Active Record errors however I cannot see my images on the FE, all I see is a broken images.

When I go into Rails c and type Service.images.last I can see that images is nil. Does anyone know why this is?

Is there anything else you need to know or see from me?

Thank you

My code to show the image:

<%=@service.images.each do  |img| %>
  <%= cl_image_tag @service.images, crop: :fill, class: 'card-image', class: 'card-image-show'%>
 <%end %>


Rails c

  Service Load (59.6ms)  SELECT  "services".* FROM "services" ORDER BY "services"."id" DESC LIMIT $1  [["LIMIT", 1]]
=> #<ActiveStorage::Attached::Many:0x00007fffc3ff08a0 @name="images", @record=#<Service id: 14, name: "Test Carpet cleaning", description: "Lorem Ipsum is simply dummy text of the printing a...", picture_url: nil, video: nil, category: "carpet cleaning", created_at: "2019-08-19 12:32:35", updated_at: "2019-08-19 12:32:35", photo: nil, images: nil>, @dependent=:purge_later>

Service model

class Service < ApplicationRecord
  has_many_attached :images
  mount_uploader :photo, PhotoUploader
end


I would like my 3 images to display on the FE

samedi 17 août 2019

How to filter out one method call from many others with `expect().to receive()` in RSpec

I have such a code:

class ClassB
  def print_letter(arg)
  end
end

class ClassA
  def self.my_method
    ClassB.print_letter("a")
    ClassB.print_letter("b")
  end
end

RSpec.describe ClassA do
  describe "self.my_method" do
    it "prints a" do
      allow(ClassB)
      expect(ClassB).to receive(:print_letter).once.with("a")
      described_class.my_method
    end
  end
end

And I'm getting a failure:

#<ClassB (class)> received :print_letter with unexpected arguments
  expected: ("a")
       got: ("b")

Can I do anything with that? Is there any way to force the receive method to analyze all method calls and pick the one where arguments match, not only the last one? BTW, this behavior seems confusing to me.

mercredi 14 août 2019

How to return in serializer custom fields in relation to ruby ​on rails?

How do I add the unit_total, price fields of a relation (orders_products) to my return in products json?

Database

orders (id, user_id, ...)

products (id, name ..)

orders_products (product_id, order_id, unit_total, price)

order_serializer.rb

class OrderSerializer < ActiveModel::Serializer
  attributes :id, :item_total, :payment_total, :quotas, :shipment_total, :additional_tax_total, :total_discount, :ip_address, :origin
  has_one :user
  has_one :address
  has_one :shipping_method
  has_many :products, serializer: OrderProductSerializer
end

order_product_serializer.rb

class OrderProductSerializer < ActiveModel::Serializer
  attributes :id, :name, :SKU, :weight, :width, :height, :depth

end

models/order.rb

class Order < ApplicationRecord
  belongs_to :user
  belongs_to :address
  belongs_to :shipping_method
  has_and_belongs_to_many :products

  [...]

end

models/product.rb

class Product < ApplicationRecord
  belongs_to :brand, optional: true
  has_and_belongs_to_many :category
  has_and_belongs_to_many :order

  [...]
end

Return

{
    "orders": [
        {
            "id": 1500,
            [...],
            "user": {
                [...]
            },
            "address": {
                [..]
            },
            "shipping_method": {
                [...]
            },
            "products": [
                {
                    "id": 12,
                    "name": "Heavy Duty Rubber Bench",
                    "SKU": "B0002BWS1G",
                    "weight": 35.0,
                    "width": 30.0,
                    "height": 20.0,
                    "depth": 100.0
                },
                {
                    "id": 10,
                    "name": "Heavy Duty Steel Wallet",
                    "SKU": "B000KJW2JS",
                    "weight": 35.0,
                    "width": 30.0,
                    "height": 20.0,
                    "depth": 100.0
                },
                {
                    "id": 10,
                    "name": "Heavy Duty Steel Wallet",
                    "SKU": "B000KJW2JS",
                    "weight": 35.0,
                    "width": 30.0,
                    "height": 20.0,
                    "depth": 100.0
                }
            ]
        }
    ]
}

How to group and sum by foreign key?

I have these two models in my Rails app:

class Person < ApplicationRecord

  has_many :payments

end


class Payment < ApplicationRecord

  belongs_to :person

end


How can I group the payments by person and order them by amount?

Right now I have...

Payment.group(:person_id).sum("amount")

...which works but doesn't include the persons' names. It returns something like this:

{ 1 => 1200.00, 2 => 2500.00 }

How can I replace the IDs / integers with the persons' names and also sort the whole thing by amount?

Thanks for any help!

Multiple Select many to many Ruby on Rails not creating associative records

Well, I have a many to many association between Contacts and Lawsuits on a table named Actives. In this case, I'm trying to add many contacts to a lawsuit. The problem is: the actives not saving in lawsuits if select is multiple, only if multiple: false.

Here's the models:

    #contact.rb
    class Contact < ActiveRecord::Base
    ...
    has_many :actives
    has_many :lawsuits, through: :actives

    #lawsuit.rb
    class Lawsuit < ActiveRecord::Base
    ...
    has_many :actives
    has_many :contacts, through: :actives

    accepts_nested_attributes_for :actives, allow_destroy: true

    #active.rb
    class Active < ActiveRecord::Base
    ...
    belongs_to :lawsuit
    belongs_to :contact

And Here's the migration table:

    class CreateActives < ActiveRecord::Migration
     def change
      create_table :actives do |t|
       t.belongs_to :contact, index: true
       t.belongs_to :lawsuit, index: true
       t.datetime :appointment_date
       t.timestamps
      end
     end
    end

The controller:

    #controller/lawsuit.rb
    #create method

    def create
      @lawsuit = Lawsuit.new(lawsuit_params)

      respond_to do |format|
        if @lawsuit.save
          format.html { redirect_to @lawsuit, notice: 'Lawsuit was successfully created.' }
          format.json { render :show, status: :created, location: @lawsuit }
        else
          format.html { render :new }
          format.json { render json: @lawsuit.errors, status: :unprocessable_entity }
        end
      end
    end

    #require params
    params.require(:contact).permit(:name, :lastname, :cpf, :rg, :birthdate, :profession_id, :marital_status_id, :address,
                                    :zipcode, :city, :state, :district, :number, :actives)

The view and output params:

    #/views/lawsuits/_form.html.erb
    <%= form_for @lawsuit, html: {class: "ui form"} do |f| %>
    ...
    <%= f.fields_for :actives do |w| %>
      <%= w.select(:contact_id, Contact.all.pluck(:name,:id), {}, {class:"selectize-generic", multiple: true})  %>
    <% end %>
    <%= f.submit %>

    #Params:
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"9dpRjs0e2iQXgYzNqObSyzuvEnVdQYVHos922hbu0UptxiVeZfJgxgbfgFGKOUR16119VFLOfheNGogAOwez/w==", 
    "lawsuit"=>{"autos"=>"", "forum_id"=>"1", "lawyer_id"=>"4", "conciliation_date"=>"", "instruction_date"=>"", "fees"=>"",
    "actives_attributes"=>{"0"=>{"contact_id"=>["", "2", "7", "9"]}}}, "commit"=>"Create Lawsuit"}

In last saved Lawsuit:

    rails c
    x = Lawsuit.last
    => #<Lawsuit id: 17, forum_id: 1, lawyer_id: 4, fees: nil, autos: "", conciliation_date: "", instruction_date: "", created_at: "2019-08-14 15:43:18", updated_at: "2019-08-14 15:43:18">
    x.actives
    => #<ActiveRecord::Associations::CollectionProxy [#<Active id: 9, contact_id: nil, lawsuit_id: 17, appointment_date: nil, created_at: "2019-08-14 15:43:18", updated_at: "2019-08-14 15:43:18">]>

I've been wasting a lot of time on this, I've already try everything, recreate models, tried simple_form gem, change in params, etc. I'm lost. Anyone can help?

GitHub for the project: https://github.com/killerowns/lawsuit-manager-rails

Force database saves on failed state transitions using Aasm State Machine gem

I am using the Aasm gem to control state changes in my App. When there is a failed transition all Database changes made inside the event are rolled back.

I have certain places in my app where I have integrated with an external API. I have the following code

event :pause do
  before do
    integration.pause(self)
  end
  transitions from: :live, to: :paused
end

This makes an Api request to the service we have integrated with. When this is successful to saves a request log. However when it fails (say a 422), then my request log that is saved to the DB is rolled back.

How do I force these types of logs to be saved when there is a failed event? And if this is not possible what are the common ways people get around this sort of problem?

thanks

lundi 12 août 2019

vendredi 9 août 2019

Net::HTTP::Get.new(uri) undefined method `request_uri' RabbitMq amqp

I want to access my rabbitmq docker container through another docker application container but I am getting the following error.

I get the error at request = Net::HTTP::Get.new(uri)

my uri string is

CLOUDAMQP_URL=amqp://guest:guest@rabbitmq:5672/%2F

def collect
      logger.info "Test 1"
      Net::HTTP.start(uri.host, uri.port, use_ssl: secure?) do |http|
        logger.info "Test 2"
        logger.info "Test URI"
        request = Net::HTTP::Get.new(uri)
        logger.info "Test URI"
        request["Accept"] = "application/json"

        request.basic_auth(uri.user, uri.password) if uri.user || uri.password
        logger.info "Test 3"
        response = http.request(request) # Net::HTTPResponse object
        logger.info "Test 4 #{request}"
        response = JSON.parse(response.body)
        response.each do |queue|
          # We're not interested in temporary queues: skip them
          # by detecting the auto_delete flag
          next if queue.fetch("auto_delete")

          name = queue.fetch("name")
          aggregator.gauge("#{name}.messages_count", queue.fetch("messages", 0))
          aggregator.gauge("#{name}.messages_rate", queue.fetch("messages_details", {}).fetch("rate", 0.0))
          aggregatr.gauge("#{name}.consumers_count", queue.fetch("consumers", 0))
        end

[ERROR] rescue: NoMethodError undefined method `request_uri' for #<URI::Generic amqp://guest:guest@rabbitmq:5672/api/queues>

I need the application to run successfully and connect to rabbitmq server

dimanche 4 août 2019

Multiple controllers with one route

I have a controller which I want to deprecate but the deprecation can't be sudden. I will create a new controller and slowly migrate users from old controller to new controller. I don't want to change the routes, basically same route should be able to direct to old controller or new controller depending on a flag. Currently I am thinking of using redirect_to to give the control to the new controller from the old one. I want to figure out the cleanest possible way to do this. Any suggestions are welcome.