Assign model to session variable in rails 4

1

I would like to know if it is possible to save an article object in a variable of session for example I have this code but it gives me this error:

  

undefined method 'add_cesta' for "#": String

This is what I'm trying to do:

This is my driver :

class TiendaController < ApplicationController


  def index
    @titulo = "Bienvenido a la Tienda"
    @articulos = Articulo.all.order("nombre").page(params[:page]).per_page(4)
  end

  def quienes_somos
    @titulo = "Bienvenido a la Tienda"      
  end

  def contacto
    @titulo = "Bienvenido a la Tienda"
  end

  def anadir_producto
      @articulo = Articulo.find(params[:id])
      @carro = sesion_carrito
      @carro.add_cesta(@articulo)
      flash[:info] ="Producto añadido #{@articulo.nombre}"      
      redirect_to inicio_url
  end

  def ver_carro
    if tenemos_sesion?
      @carro = session[:carro]
    else
      flash[:info] = "Donde Vas! Compra antes"
      redirect_to inicio_url
    end
  end

  def vaciar_carrito
      session[:carro] = nil
      flash[:info] = "Carrito vacio"
      redirect_to inicio_url
  end

  private

  def tenemos_sesion?
    session[:carro]
  end

  def sesion_carrito      
      session[:carro] ||= Carro.new
  end
end

this is my class carro.rb within models:

class Carro
  attr_reader :cesta

  def initialize
    @cesta = []
  end

  def add_cesta(articulo)
    @cesta << articulo    
  end

end

Theoretically it should work, I have not got something that tells me that you can not but also something that supports you, someone can tell me if it is possible and if I can I'm doing wrong.

    
asked by Angel Bastidas 08.09.2017 в 04:23
source

1 answer

0

Good practices say that it is not advisable to save models in session variables. What you should do is save only an arrangement with the id of the articles. Something like that would be better:

session[:carrito] ||= []
session[:carrito] << @artículo.os

And then when you want to work with the articles you can retrieve them using

@articulos_en_carrito = Artículo.where(id: session[:carrito])
    
answered by 04.10.2017 в 00:02