I
I
Ilnar252017-09-08 18:12:42
Ruby on Rails
Ilnar25, 2017-09-08 18:12:42

How to store geocoder gem data in sessions without storing it in the database?

The point is simple. The Order model has the address of its recipient and separately the address of its sender. Task: how to store the recipient address data in sessions before the order is created, since it is necessary to calculate the cost of the order given the recipient address data and store them together at the same time in the Order model. I would like to save it in advance in sessions in order to avoid unnecessary database updates and just unnecessary create and unnecessary find. Just what is the best way to implement it?

class Order < ApplicationRecord
  belongs_to :user, optional: true
  serialize :order_info
 
  geocoded_by :recipient_adress, :latitude  => :recipient_latitude, :longitude => :recipient_longitude
  after_validation :geocode, if: ->(obj){ obj.recipient_adress.present?}
end

class OrdersController < ApplicationController
  include OrderHelper
  before_action :authenticate_user!
  before_action :check_session, only: [:pre_order]

  expose_decorated :orders, ->{current_user.orders}
  expose_decorated :order

  def create
    @order = current_user.orders.build(order_params)
    @order.order_info = session[:cart]
    if @order.save
      redirect_to root_path, notice: "Successfully"
    else
      flash[:notice] = "Please enter a valid address!"
      render 'pre_order'
    end
  end

  def recipient_adress
  end

  def pre_order
    @current_order = session[:cart].values
    @cost_of_shipping = session[:cost_of_shipping]
  end

  def destroy
  end

  def show
    render component: 'Orders', props: { orders: orders }
  end

  private

    def check_session
      redirect_to root_path if session[:cart] == nil
    end

    def order_params
      params.require(:order).permit(:recipient_adress)
    end
end

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilnar25, 2017-09-08
@Ilnar25

Thank you! Found the answer. You just had to write in the controller like this

def create
    @order = Order.new(order_params)
    session[:attr] = Geocoder.coordinates(@order.recipient_adress)
  end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question