1

I have a Ruby on Rails application where you can create 'posts'. I started of by using the scaffold generator to give generate the title which is a string and the body which is the content.

Each 'post' has a url of the id, for example /1, /2, /3, etc.

Is there a way to change it to generater a string of random characters and numbers, for example /49slc8sd, /l9scs8dl, etc?

Here is what I have for the posts_controller.rb

class PostsController < ApplicationController
  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
    @post = Post.find(params[:id])

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

  # GET /posts/new
  # GET /posts/new.json
  def new
    @post = Post.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @post }
    end
  end

  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.json
  def create
   @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /posts/1
  # PUT /posts/1.json
  def update
    @post = Post.find(params[:id])

    respond_to do |format|
      if @post.update_attributes(params[:post])
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post = Post.find(params[:id])
    @post.destroy

    respond_to do |format|
      format.html { redirect_to posts_url }
      format.json { head :no_content }
    end
  end
end

And here is what I have in the post.rb model

class Document < ActiveRecord::Base
  attr_accessible :content, :name
end
4

5 に答える 5

1

ActiveRecord::Base オブジェクトのto_paramメソッドにも注意してください。

基本的に、Rails はオブジェクトでこのメソッドを呼び出して、URL と params[:id] に何を入れるかを認識します。デフォルトでは、データベース内のレコードの主キーのみです。次のようにオーバーライドするとします。

class Post < ActiveRecord::Base

  def to_param
    return id*100
  end

  def self.find_by_new_id(n)
    return self.find(n/100) # really you'd want to handle strings and integers
  end
end

データベースの最初のレコードには url があります/posts/100

コントローラーで、今行っているオブジェクトを取得するには

@post = Post.find_by_new_id(params[:id])

(もちろん、デフォルトのfindメソッドをオーバーライドすることもできますが、それはおそらく眉をひそめられるでしょう。) 基本的に、to_paramメソッドは ID を変換し、新しいファインダーはそれを元に戻します。通常、レコードの作成時にフックを介して自動的に入力された別のデータベース列を指定するだけです。これは、Qumara otBurgas が投稿したリンクに記載されている内容です。

于 2012-11-24T08:46:45.403 に答える
1

モデルにプライマリ キー ID を予測可能な順序で持たせたくない場合は、 http: //codesnipers.com/?q=using-uuid-guid- のようなものを使用して、uuid または GUID に基づいて ID を生成できます。 as-primary-key-in-rails

ただし、ルートでデータベース識別子を公開したくない場合に推奨されるアプローチであるリソースを一意に識別する他のプロパティに基づいてルーティングすることもできます

person/:person_random_token, :controller => :persons, :action => :show #adding this in your route file directing to the controller where you can use params[:person_random_token] to uniquely identify your person object in Persons model

コントローラーのアクションで、次のように言うことができます

Person.find_by_random_token(params[:person_random_token]) #assuming random_token is your column name

Person オブジェクトを取得するには

于 2012-11-23T20:20:44.057 に答える
1

数値 ID を難読化したい場合は、この興味深い議論をご覧ください

于 2012-11-23T20:24:27.120 に答える
0

Rubyでランダムな文字列を生成する方法はいくつかあります。

さて、あなたの質問の2番目の部分に。のようなルートを使用して投稿にアクセスする場合は/post/rndm5tr、コントローラー内の次のコード行を変更するだけです。

@post = Post.find(params[:id])

@post = Post.find_by_randomness(params[:id])

次に、移行を作成してrails g migration AddRandomnessToPost randomness:string実行しますrake db:migrate(またはbundle exec rake db:migrate、設定方法によっては、実行します)。

もちろん、フィールドには好きな名前を付けることができますrandomness。これは私が使用したランダムな名前です。一般的な慣習はそれらをスラッグまたはトークンと呼ぶことだと思いますが、私は間違っているかもしれません。

次に、モデルにメソッドを追加しbefore_createてランダムな文字列を生成し、それを間もなく保存されるPostオブジェクトに追加します(上記のリンクの例の1つを使用)。生成している文字列がすでに使用されているかどうかを確認することをお勧めします(投稿にすでにランダムトークンがある場合は、自分自身を再度呼び出す再帰メソッドを作成できます)。

于 2012-11-24T02:17:31.697 に答える
0

あなたがここで何を求めているのかは明らかではありません。ルートで指定されたアクションへのパスでは、渡される ID が特定の形式である必要はありません。必要に応じて数値以外の ID を渡すことができ、アクション内で任意の方法で ID を使用できます。ルートとアクションに関する詳細情報を提供していただければ、ご要望を理解できるかもしれません。

于 2012-11-23T19:59:44.933 に答える