如果我有这样的嵌套资源:
resources :users
resources :posts
end
和一个 user
has_many
posts
,是否可以让 Rails 根据 URL 中的父关联开始编号?比如目前嵌套资源只是抓取ID:
@user.posts.find(params[:id])
这正确地命名了帖子,只允许来自 @user
的帖子......但是,有没有办法让 post_id
是独立的? IE。我希望每个用户的帖子都从 1 开始,其中:
/users/1/posts/1
/users/2/posts/1
实际上指的是两个不同的帖子?
最佳答案
这可能需要相当多的工作,但基本上您可以通过以下步骤完成:
- 创建一个迁移以添加一个新属性来存储特定的用户帖子数。 (我使用了
user_post_id
) - 覆盖
Post
的to_param
方法以使用您刚刚创建的新值。 (它必须是一个字符串。)to_param
是url
和path
助手使用的方法。
- 创建一个
before_save
过滤器,它实际上会增加每个新帖子的user_post_id
值。 更改所有 Controller 方法以在
user_post_id
上查找@user = User.find(params[:user_id]) @post = @user.posts.where(:user_post_id => (params[:id])).first
- 更改所有现在可能不起作用的 View
您可以在此处查看来源:Custom Nested Resource URL example
代码
迁移:
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
一些 Controller 方法 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
关于ruby-on-rails - Rails 嵌套关联和重新编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8752120/