开发者

Rails ordering relationship output

开发者 https://www.devze.com 2023-04-01 22:41 出处:网络
I have a rails application in which pages has many comments.So the relationships in the models开发者_Python百科 are:

I have a rails application in which pages has many comments. So the relationships in the models开发者_Python百科 are:

page.rb: has_many :comments

comment.rb: belongs_to :page

Now I display the comments in my view by doing:

<% @page.comments.each_with_index do |comment| %>
   <%= comment.comment %>
<%end%>

I want to know how I can paginate this with will_paginate. I also want to make it so that the newest one (one with greatest id shows up first). Any ideas?


To order the comments:

has_many :comments, :order => "id DESC"

To use will_paginate just push the logic into your controller:

@comments = @page.comments.paginate(:page => params[:page])


You could use scopes to provide this feature. Scopes are essentially a way of filtering and/or ordering ActiveRecord models when asking for collections.

Scopes are a little different between Rails 2.x and 3.x. In Rails 2.x you can use named_scope and default_scope.

class Comment < ActiveRecord::Base
  default_scope :order => "id DESC"
end

Not surprising, default_scope defines a default scope used when fetching your records, as in a Comment.find_by_page_id(100). Will paginate should fetch your records using the default scope you've defined.

In Rails 3.x you define a default scope like:

class Comment < ActiveRecord::Base
  default_scope order("id DESC")
end

Hope this helps.


Not sure about the pagination but you can query with an order like this:

@page.comments.find(:all, :order => "id desc")

Maybe will_paginate will take care of the rest?

EDIT: As per John's comment (thanks!) the Rails 3 way is indeed:

@page.comments.order("id desc")
0

精彩评论

暂无评论...
验证码 换一张
取 消