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

What is the best data type for storing pictures in the active records. (Rails)

What is the best Data Type for storing pictures in rails? I am currently creating my models using the ActiveRecord and I am a bit confused.

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.