绕过 Rails 中的控制器
我使用 Rails 2.3.5,我有一个模型,我们称之为 Post。我使用命名范围在 Post 上应用不同类型的排序。例如,在 Post 模型中,我可以按分数对帖子进行排名:
named_scope :order_by_acception_rate_desc,
Proc.new { |limit| { :limit => limit, :order => "acception_rate desc" } }
在 Post 控制器中,我有:
def best
@best_posts = Post.order_by_acception_rate_desc(10)
end
在视图中,我只是渲染此集合 @best_posts:
<%= render :partial => "post", :collection => @best_posts
目前我的应用程序正在这样工作,但实际上我不需要在控制器中具有“最佳”方法,我可以将其移动到模型帖子中,如下所示:
def self.best
self.order_by_acception_rate_desc(10)
end
然后在视图中我将呈现集合,如下所示:
<%= render :partial => "post", :collection => Post.best
我不知道哪种方法更好,但使用中的排名方法模型,我可以避免为每个排名创建路线 方法。什么方法更好,还有比这些更好的方法吗?
Im using Rails 2.3.5 and I have a model, let's call it Post. I used named scopes to apply different kinds of sorts on Post. For example, in the Post model I have possibility to rank posts by its scores:
named_scope :order_by_acception_rate_desc,
Proc.new { |limit| { :limit => limit, :order => "acception_rate desc" } }
In the Post Controller I have:
def best
@best_posts = Post.order_by_acception_rate_desc(10)
end
In the view I just render this collection @best_posts:
<%= render :partial => "post", :collection => @best_posts
Currently my application is working like that, but actually I do not need to have the method "best" in the Controller, and I could move it to the Model Post doing like:
def self.best
self.order_by_acception_rate_desc(10)
end
and then in the view I would render the collection like:
<%= render :partial => "post", :collection => Post.best
I do not know which approach is better, but using the ranking methods in the Model, I could avoid to create routes for each one of ranking methods. What approach is better, is there any better approach than these?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 Rails 约定,逻辑应该分开,
我想请你尝试一下:
with according to Rails conventions the logic should be separated,
I'd like to ask you to try:
您不应该绕过控制器并在视图中包含太多逻辑。
您可以保留单个路由并根据
params
之一过滤Post
模型。您在这里没有说得足够多,无法更清楚地回答,但您已经了解了大局。
You should not bypass the controller and include much logic in your view.
You could keep a single route and filter the
Post
model depending on one of theparams
.You don't tell enough here to answer more clearly but you have the big picture.
您可以只保留视图文件,它应该可以工作。
You can leave just the view file and it should work.