开发者

Creating a hash and using to_param to obfuscate ids

I'd like to be able to obfuscate the id's of objects in my app so that a URL can be shared, but not easily guessed.

I've gathered that I need to store a ha开发者_StackOverflow社区shed_id in the database for the object, and that it may be possible to rewrite the to_param function to use that hashed_idin the URL but I'm having trouble getting it to work.

model:

  after_create :create_hashed_id

  def to_param
        self.hashed_id
  end

  def create_hashed_id
    self.update_attributes(:hashed_id => Digest::SHA1.hexdigest([Time.now, rand].join)[0,16])
  end

controller:

def show
    @upload = Upload.find_by_hashed_id(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @upload }
    end
  end

The object gets created with a hash_id attribute but when I try and invoke the show method it looks like it's looking in the id column instead of the hashed_id column.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜