Question

Hi hopefully somebody can help me out. I'm a bit stuck at the moment. I'm trying to create an app for a tracking system, I currently have a table called sdel_hashed. Following online videos I so far set up digest/sha1 to work partly. If I enter the following commands in the console:

sdel = Sdel.find(1)
sdel.hashed_sdel = Sdel.hash('secret')
sdel.save

And then view the record in the browser it show up as the hash and not secret, but if I try and enter the word secret through the new action it doesn't get hashed. I think there is maybe something missing in the create action but I cannot find answers anywhere. i would greatly appreciate any help. I'll include now what I have in my controller and model. Thanks

model sdel

require 'digest/sha1'
class Sdel < ActiveRecord::Base
  attr_accessible :hashed_sdel

  def self.hash(sdel="")
     Digest::SHA1.hexdigest(sdel)
  end

end

controller sdels

class SdelsController < ApplicationController
  def list
    @sdel = Sdel.all
  end

  def new
    @sdel = Sdel.new
  end

  def create
    @sdel = Sdel.new(params[:sdel])
    if @sdel.save
      redirect_to(:action => 'list')
    else
      render('new')
    end
  end
end

Migration file

class CreateSdels < ActiveRecord::Migration
  def change
    create_table :sdels do |t|
      t.string "hashed_sdel"
      t.timestamps
    end
  end
end
Was it helpful?

Solution

Sounds like you may want to use a before_save filter to invoke the hash class method on the Sdel model prior to saving when the attribute has been modified. Perhaps something along the lines of this:

require 'digest/sha1'

class Sdel < ActiveRecord::Base
  attr_accessible :hashed_sdel

  before_save { self.hashed_sdel = self.class.hash(hashed_sdel) if hashed_sdel_changed? }

  def self.hash(sdel="")
    Digest::SHA1.hexdigest(sdel)
  end
end

This way, if you have a form that has a text_field for your hashed_sdel attribute, it will automatically get run through the hash class method you have before it the record gets saved (assuming the attribute has changed from it's previous value).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top