Rails嵌套关联并重新启动编号

如果我有这样的嵌套资源:

resources :users resources :posts end 

并且user posts ,Rails可以根据URL中的父关联开始编号吗? 例如,目前,嵌套资源只是获取ID:

 @user.posts.find(params[:id]) 

这正确地命名post,只允许来自@userpost…但是,有没有一种方式使post_id是独立的? IE我希望每个用户的post从1开始,其中:

 /users/1/posts/1 /users/2/posts/1 

实际上是指两个不同的post?

这可能是相当多的工作,但基本上你可以通过以下步骤来做到这一点:

  1. 创建迁移以添加新属性以存储特定的用户发布计数。 (我使用了user_post_id
  2. 覆盖Postto_param方法以使用刚刚创建的新值。 (它必须是一个字符串。)
    • to_paramurlpath helpers使用的方法。
  3. 创建一个before_savefilter,它将实际增加每个新post的user_post_id值。
  4. 更改所有控制器方法以在user_post_iduser_post_id

     @user = User.find(params[:user_id]) @post = @user.posts.where(:user_post_id => (params[:id])).first 
  5. 更改可能现在不起作用的所有视图

您可以在此处查看源: 自定义嵌套资源URL示例

移民:

 class AddUserPostIdToPosts < ActiveRecord::Migration def change add_column :posts, :user_post_id, :integer end end 

post.rb:

 class Post < ActiveRecord::Base before_save :set_next_user_post_id belongs_to :user validates :user_post_id, :uniqueness => {:scope => :user_id} def to_param self.user_post_id.to_s end private def set_next_user_post_id self.user_post_id ||= get_new_user_post_id end def get_new_user_post_id user = self.user max = user.posts.maximum('user_post_id') || 0 max + 1 end end 

一对夫妇控制器方法posts_controller.rb:

 class PostsController < ApplicationController respond_to :html, :xml before_filter :find_user def index @posts = @user.posts.all respond_with @posts end def show @post = @user.posts.where(:user_post_id => (params[:id])).first respond_with [@user, @post] end ... end