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?
with according to Rails conventions the logic should be separated,
- controllers handle permissions, auth/authorization, assign instance/class variables
- helpers handle html logic what to show/hide to user
- views should not provide any logic, permissions check. think about it from designer's point of view
- models handle data collection/manipulation over ORM
I'd like to ask you to try:
#helper
def self.best(limit)
all(:limit => limit, :order => "acception_rate desc")
end
#controller
@best_posts = Post.best
#view
<%= render :partial => "post", :collection => @best_posts %>
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 the params
.
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.
精彩评论