Rails 嵌套关联并重新编号 [英] Rails nested association and restarted numbering

查看:40
本文介绍了Rails 嵌套关联并重新编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

  1. 创建迁移以添加新属性来存储特定的用户帖子计数.(我使用了 user_post_id)
  2. 覆盖Postto_param 方法以使用您刚刚创建的新值.(它必须是一个字符串.)
    • to_paramurlpath 助手使用的方法.
  1. Create a migration to add a new attribute to store the specific user-post count. (I used user_post_id)
  2. Override Post's to_param method to use the new value you just created. (It has to be a string.)
    • to_param is the method that the url and path 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆