Rails博客应用的高级优化与美化
立即解锁
发布时间: 2025-08-20 01:21:01 阅读量: 1 订阅数: 3 


Rails 3入门:从零开始构建Web应用
### Rails博客应用的高级优化与美化
#### 1. 收尾工作概述
在完成大部分工作后,还需对模板进行优化、确保文章所有者可编辑和删除文章、更新布局并应用CSS样式。以下是具体操作步骤:
- **使用Action View助手**:Rails提供了多种格式化助手,可用于清理模板。
- **数字助手**:`NumberHelper`模块可将数字转换为格式化字符串,提供电话号码、货币、百分比等格式化方法。详情见[NumberHelper文档](http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html)。
- **文本助手**:`TextHelper`模块提供了过滤、格式化和转换字符串的方法,可减少视图中的内联Ruby代码。详情见[TextHelper文档](http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html)。
- **URL助手**:Rails提供了一组URL助手,使构建依赖于控制器和动作的链接变得简单。`link_to`是一个常用的URL助手,其语法如下:
```ruby
link_to(name, options={}, html_options={})
```
参数说明:
| 参数 | 说明 |
| ---- | ---- |
| 第一个参数 | 链接的名称 |
| 第二个参数 | 要链接的URL,可以是字符串、命名路由或用于生成URL的选项哈希,也可以是对象,Rails会将其替换为显示动作的命名路由 |
| 第三个参数 | 生成标签的HTML选项哈希 |
示例:
```ruby
link_to 'New', new_article_path, :id => 'new_article_link'
link_to 'New', {:controller => 'articles', :action => 'new'}, :class => 'large'
```
#### 2. 模板中的HTML转义
为防止恶意用户注入任意HTML代码,应始终在视图中显示HTML之前对其进行转义。Rails会自动转义所有渲染的字符串。若要显示用户输入的原始字符串,可使用`raw`方法。例如,在`app/views/articles/_article.html.erb`中显示文章正文的原始格式:
```ruby
raw(article.body)
```
#### 3. 正文区域的格式化
使用`simple_format`文本助手可改善正文区域的显示效果。该助手根据简单的格式化规则将文本转换为HTML,连续两个或更多换行符视为段落并包裹在`<p>`标签中,一个换行符视为换行并追加`<br />`标签。在`app/views/articles/_article.html.erb`中添加以下代码:
```ruby
<%= div_for article do %>
<h3>
<%= link_to article.title, article %>
<span class='actions'>
<%= link_to "Edit", edit_article_path(article) %>
<%= link_to "Delete", article, :confirm => "Are you sure?", :method => :delete %>
</span>
</h3>
<%= simple_format article.body %>
<% end %>
```
#### 4. 添加编辑控件
为防止用户编辑或删除他人的文章,需在`Article`模型中添加`owned_by?`方法,用于判断文章是否由指定用户拥有。在`app/models/article.rb`中添加以下代码:
```ruby
class Article < ActiveRecord::Base
validates :title, :presence => true
validates :body, :presence => true
belongs_to :user
has_and_belongs_to_many :categories
has_many :comments
scope :published, where("articles.published_at IS NOT NULL")
scope :draft, where("articles.published_at IS NULL")
scope :recent, lambda { published.where("articles.published_at > ?", 1.week.ago.to_date)}
scope :where_title, lambda { |term| where("articles.title LIKE ?", "%#{term}%") }
def long_title
"#{title} - #{published_at}"
end
def published?
published_at.present?
end
def owned_by?(owner)
return false unless owner.is_a? User
user == owner
end
end
```
然后,在文章和评论部分中,仅当文章由当前登录用户拥有时才显示编辑或删除链接。在`app/views/articles/_article.html.erb`和`app/views/comments/_comment.html.erb`中添加相应代码:
```ruby
# app/views/articles/_article.html.erb
<%= div_for article do %>
<h3>
<%= link_to article.title, article %>
<% if article.owned_by? current_user %>
<span class='actions'>
<%= link_to "Edit", edit_article_path(article) %>
<%= link_to "Delete", article, :confirm => "Are you sure?", :method => :delete %>
</span>
<% end %>
</h3>
<%= simple_format article.body %>
<% end %>
# app/views/comments/_comment.html.erb
<%= div_for comment do %>
<h3>
<%= comment.name %> <<%= comment.email %>> said:
<% if @article.owned_by? current_user %>
<span class='actions'>
<%= link_to 'Delete', [@article, comment], :confirm => 'Are you sure?', :method => :delete %>
</span>
<% end %>
</h3>
<%= comment.body %>
<% end %>
```
#### 5. 确保文章有所有者
为确保添加文章时分配用户,需更新`articles`控制器中的`create`方法,使用`current_user.articles.new`来实例化文章对象,将`user_id`字段设置为当前用户的ID。同时,将`edit`、`update`和`destroy`动作修改为仅检索当前登录用户的文章。在`app/controllers/articles_controller.rb`中进行以下修改:
```ruby
class ArticlesController < ApplicationController
before_filter :authenticate, :except => [:index, :show]
# GET /articles
# GET /articles.xml
def index
@articles = Article.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @articles }
end
end
# GET /articles/1
# GET /articles/1.xml
def show
@article = Article.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @article }
end
end
# GET /articles/new
# GET /articles/new.xml
def new
@article = Article.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @article }
end
end
# GET /articles/1/edit
def edit
@article = current_user.articles.find(params[:id])
end
# POST /articles
# POST /articles.xml
def create
@article = current_user.articles.new(params[:article])
respond_to do |format|
if @article.save
format.html { redirect_to(@article, :notice => 'Article was successfully created.') }
format.xml { render :xml => @article, :status => :created, :location => @article }
else
format.html { render :action => "new" }
format.xml { render :xml => @article.errors, :status => :unprocessable_entity }
end
end
end
# PUT /articles/1
# PUT /articles/1.xml
```
0
0
复制全文
相关推荐










