Search code examples
ruby-on-railsruby-on-rails-3associationsforeign-key-relationshipmodel-associations

List of post revisions


I need help gathering a list of post revisions. Users should be able to see this same list whether on the original post or any following revision of the post. I know that I have to somehow use the foreign key (revision_id) to pull the other revisions when the current post is a revision, but I don't know how.

Also, if there's a better way to do this, I'm up for the suggestions.

post.rb

class Post < ActiveRecord::Base
    #...
    has_many :revisions, class_name: "Post", foreign_key: "revision_id"
    #...
end

posts_controller.rb

 class PostsController < ApplicationController
     def show
         @post = Post.find(params[:id])

         if @post.revision_id = nil
             @original = @post
         else
             @original = @post.revision_id
         end

         @revisions = @original.revisions.all
          #...
     end
 end

Solution

  • If I understand the problem correctly, post can have many revisions but revision can belong to only one post. If so, you don't need has_and_belongs_to_many relation and you can use has_many/belongs_to relations, as follows:

    class Post < ActiveRecord::Base
      has_many :revisions, class_name: 'Post', foreign_key: 'revised_id'
      belongs_to :revised, class_name: 'Post'
    end
    

    So now you can do in your controller:

    if @post.revision_id.nil?
      @original = @post
    else
      @original = @post.revised
    end
    
    @revisions = @original.revisions
    

    or you can move this to model:

    def original
      revised_id.present? ? revised : self
    end
    

    and then you can tidy up your controller:

    @revisions = @post.original.revisions