If I have a nested resource like so:
resources :users
resources :posts
end
and a user
has_many
posts
It can be quite a bit of work, but basically you can do it with these steps:
user_post_id
)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.before_save
filter that will actually increment the user_post_id
value for each new post.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
You can see the source here: Custom Nested Resource URL example
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