我想在 and 之间有一个简单的belongs_to
andhas_many
关系。我通常会这样做:Post
Comment
路线:
resources :posts do
resources :comments
end
模型:设置默认页面大小:
class Comments < ActiveRecord::Base
belongs_to :post
DEFAULT_PAGE_SIZE = 25
end
控制器:
class CommentsController
def index
post = Post.find(params[:post_id])
offset = params[:offset] || 0
limit = params[:limit] || Comment::DEFAULT_PAGE_SIZE
@comments = post.comments.offset(offset).limit(limit)
respond_to do |format|
#respond as you like
end
end
# more actions...
end
查看,加载更多链接之类的,以通过 ajax 加载评论:
<%= link_to "load more comments", post_comments_path(@post, :format => 'js'), :method => :get, :remote=>true id='load-more-comments' %>
并且您还想将偏移量绑定到 ajax 帖子:
$ ->
$('#load-more-comments').on 'ajax:before', (event) ->
el = $(this)
offset = #count your offset, I often do by counting the <li>s already in the <ul>
el.data 'params', "offset=#{offset}"
# you could also pass the limit: el.data 'params', "offset=#{offset}&limit=#{some limit}"
.on 'ajax:complete', (event, xhr, status) ->
el = $(this)
el.removeData 'params' # remember to remove this.
我也对这样做的更好方法感兴趣。期待答案和批评。:)