views:

133

answers:

2

Hi, little help needed

got 2 models:

class User < ActiveRecord::Base
  has_many :posts
end

and

class Post < ActiveRecord::Base
  belongs_to :user
end

the Posts table has a column: u_hash. This is supposed to be a randomly generated identifying hash (for public viewing). What is the best way to generate this hash and how can I add it to the table? The idea is that all this will happen in the background and not be visible to the user (no hidden field in the form). The database used is MySQL if that could help me out somehow.

Thanks in advance! J

A: 

This sounds like a job for ActiveRecord callbacks.

If your posts tables has a before_create callback, you can create and set a value automatically every time a new post instance is created.

e.g.:

class Post < ActiveRecord::Base
  belongs_to :user

  before_create  :set_uhash_column

  private

  def set_uhash_column
    #your code here - something like self.uhash = ...
  end
end
DanSingerman
+2  A: 

You most likely need before_validation_on_create callback for your Post model. This callback is internally called by ActiveRecord functionality when you save a new Post record into database.

A good callback reference and a hint of the order callbacks are called in you can find here.

Here's a code, that explains why it is before_validation_on_create that you need to use:

class Post < ActiveRecord::Base
  belongs_to :user
  validates_uniqueness_of :u_hash
  before_validation_on_create :generate_u_hash

  def generate_u_hash
    begin
      new_u_hash = "random hash here"
    end while Post.find_by_u_hash(new_u_hash)
    self.u_hash = new_u_hash
  end
end
Pavel Shved
Thanks, this worked perfectly.
Jaan J
just to help anyone else with the same problem: new_u_hash = Digest::SHA256.hexdigest("-#{Time.now.to_s}--#{self.title}--")[0,15]there the title is entered by the user :)
Jaan J