Rails nested association and restarted numbering

前端 未结 1 1283
独厮守ぢ
独厮守ぢ 2020-12-16 08:57

If I have a nested resource like so:

resources :users
  resources :posts
end

and a user has_many posts

相关标签:
1条回答
  • 2020-12-16 09:12

    It can be quite a bit of work, but basically you can do it with these steps:

    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.
    3. Create a before_save filter that will actually increment the user_post_id value for each new post.
    4. 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
      
    5. Change all your Views that might not work now

    You can see the source here: Custom Nested Resource URL example

    Code

    migration:

    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
    

    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
    
    0 讨论(0)
提交回复
热议问题