您只需要添加一个属性到post
. 属性名称是permalink
。
尝试运行:
rails g migration add_permalink_to_posts permalink:string
rake db:migrate
您有两个Active Record 回调可供选择:before_save
或before_create
(查看两者之间的区别)。此示例使用before_save
回调。
注意:对于 Rails 3.x
class Post < ActiveRecord::Base
attr_accessible :content, :permalink
before_save :make_it_permalink
def make_it_permalink
# this can create a permalink using a random 8-digit alphanumeric
self.permalink = SecureRandom.urlsafe_base64(8)
end
end
urlsafe_base64
在你的routes.rb
文件中:
match "/post/:permalink" => 'posts#show', :as => "show_post"
在posts_controller.rb
:
def index
@posts = Post.all
end
def show
@post = Post.find_by_permalink(params[:permalink])
end
最后,以下是意见(index.html.erb
):
<% @posts.each do |post| %>
<p><%= truncate(post.content, :length => 300).html_safe %>
<br/><br/>
<%= link_to "Read More...", show_post_path(post.permalink) %></p>
<% end %>