开发者

Set default random column value in ActiveRecord model

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 ge开发者_运维技巧nerate 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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜