我在尝试让 AR finders 在我的应用程序中保持干燥时遇到了问题。我创建了一个博客应用程序,当用户第一次查看博客时,它会获取博客的所有相关页面、帖子、链接、标签和类别。博客 Controller 的示例显示操作如下所示:
def show
#find blog by user name
@user= User.find_by_login(params[:id])
@blog= @user.blog
@posts = Post.status("publish",@user).find(:all, :order => "created_at DESC")
@tags = @user.tags
@pages = Page.status("publish",@user).find(:all, :order => "created_at DESC")
@links = @user.links.public_link.find(:all, :order => 'created_at DESC')
@archives = @posts.group_by(&:month)
@categories = @user.categories.group_by(&:name)
session[:found_user]=@user.login
render :layout=>false
end
如您所见,它不是很 DRY,因为 Controller 中还有其他操作会调用相同的实例变量,例如 @tags 等。
我怎样才能让它更干?我尝试将它移动到博客模型中,但我仍然需要在 Controller 中调用各种实例变量,例如 @tags 等。
有没有办法在第一次调用博客时存储所有这些变量并跨 Controller 和操作重用它们?
感谢您的任何建议。我正在使用 Rails 2.1
我在某处的博客上读到,用辅助方法简单地替换过滤器前(或在 Controller 方法中加载各种数据)。像这样:
class BlogsController < ApplicationController
def show
session[:found_user]=@user.login
render :layout=>false
end
helper_method :user, :blog, :posts, :tags, :pages, :links, :archives, :categories
protected
def user
@user ||= User.find_by_login(params[:id])
end
def blog
@blog ||= user.blog
end
def posts
@posts ||= Post.status("publish", user).find(:all, :order => "created_at DESC")
end
def tags
@tags ||= user.tags
end
def pages
@pages ||= Page.status("publish", user).find(:all, :order => "created_at DESC")
end
def links
@links ||= user.links.public_link.find(:all, :order => 'created_at DESC')
end
def archives
@archives ||= posts.group_by(&:month)
end
def categories
@categories ||= user.categories.group_by(&:name)
end
end
## app/views/blogs/show.html.erb
Name: <%=h user.name %>
<%= posts.length %> Posts
<% posts.each do |post| %>
...
<% end %>
<% categories.each do |category| %>
- <%=h category %>
<% end %>
看看如何在 View 中使用任何东西简单地调用数据库。此解决方案的一个优点是未调用的辅助方法不会占用操作时间。
如有必要,将辅助方法抽象为一个模块并将该模块包含在 ApplicationController 中。
Tôi là một lập trình viên xuất sắc, rất giỏi!