Rails 嵌套关联并重新编号 [英] Rails nested association and restarted numbering
问题描述
如果我有这样的嵌套资源:
If I have a nested resource like so:
resources :users
resources :posts
end
和 user
has_many
posts
,是否可以根据 URL 中的父关联让 Rails 开始编号?例如,目前,嵌套资源只是抓取 ID:
and a user
has_many
posts
, it is possible to have Rails start numbering based on the parent association in the URL? For example, currently, nesting resources just grabs the ID:
@user.posts.find(params[:id])
这正确命名了帖子,只允许来自 @user
的帖子......但是,有没有办法使 post_id
是独立的?IE.我希望每个用户的帖子从 1 开始,其中:
This correctly namespaces the posts, only allowing posts from @user
... however, is there a way such that the post_id
is independent? I.E. I want each user's posts to start at 1, where:
/users/1/posts/1
/users/2/posts/1
实际上是指两个不同的帖子?
Actually refer to two different posts?
推荐答案
这可能需要很多工作,但基本上您可以通过以下步骤完成:
It can be quite a bit of work, but basically you can do it with these steps:
- 创建迁移以添加新属性来存储特定的用户帖子计数.(我使用了
user_post_id
) - 覆盖
Post
的to_param
方法以使用您刚刚创建的新值.(它必须是一个字符串.)to_param
是url
和path
助手使用的方法.
- Create a migration to add a new attribute to store the specific user-post count. (I used
user_post_id
) - Override
Post
'sto_param
method to use the new value you just created. (It has to be a string.)to_param
is the method that theurl
andpath
helpers use.
更改所有控制器方法以在 user_post_id
Change all your controller methods to find on user_post_id
@user = User.find(params[:user_id])
@post = @user.posts.where(:user_post_id => (params[:id])).first
您可以在此处查看源代码:自定义嵌套资源 URL 示例
You can see the source here: 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
几个控制器方法post_controller.rb:
A couple controller methods 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
这篇关于Rails 嵌套关联并重新编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!