Search code examples
ruby-on-railsmodelattributescreated-at

Rails how assign created_at in a model and / or model callback to an attribute


I am building an e-commerce app. I want to assign created_at to an attribute.

Stale Product inventory is 'sent' / 'submitted' to the SaleController, creating a product on sale.

  1. I am trying to assign the time created_at to sale_start_time - an attribute of the model Sale - which I can later use to trigger mark-downs, for example, @sale_start_time+5day . In the Sale model:
     def sale_start_time
         @sale.created_at
     end
    
    

That does not work, nor does @sale_start_time = @sale.created_at -- even though in a view, for example sales#show, @sale.created_at returns the created_at time.

  1. I also tried placing it in a Sale model after commit (although I can't determine if two attributes can be changed in a single after commit). Product does toggle product_on_sale: false to product_on_sale: true (which, practically speaking, removes it from product inventory). The Sale update of the attribute doesn't work. It 'raises' 'id'={:id=>nil} I'd user Sale.find_by(@product_id)... however, product_id may not equal sale_id.

    def update_status
       Product.find_by(@product_id).toggle!(:product_on_sale)
       Sale.find(id: @id).update(sale_start_time: @sale.created_at)
    end
    

Thank you in advance for your help.


Solution

  • If I understood your question correctly, you can assign it in a after_create callback.

    In the Sale model add this:

    class Sale
      # other stuff
      after_create :assign_start_time  
    
      # other methods
    
      private
    
      def assign_start_time
        self.sale_start_time = created_at
        self.save!
      end
    end
    

    Edit by OP: This works IF the controller method def create defines sale as @sale = Sale.create(sale_params) 'create' sets the sale id. I was using @sale = Sale.new(sale_params) which does not set the sale id until the transaction is committed.