【问题标题】:List of post revisions后期修订列表
【发布时间】:2013-06-25 20:47:08
【问题描述】:

我需要帮助收集修订后的列表。用户应该能够在原始帖子或帖子的任何后续修订中看到相同的列表。我知道当当前帖子是修订版时,我必须以某种方式使用外键(revision_id)来提取其他修订版,但我不知道如何。

另外,如果有更好的方法可以做到这一点,我愿意接受建议。

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 associations foreign-key-relationship model-associations


    【解决方案1】:

    如果我正确理解问题,post 可以有多个revisions,但revision 只能属于一个post。如果是这样,你就不需要has_and_belongs_to_many关系,你可以使用has_many/belongs_to关系,如下:

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

    所以现在你可以在你的控制器中做:

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

    或者您可以将其移至模型:

    def original
      revised_id.present? ? revised : self
    end
    

    然后你就可以整理你的控制器了:

    @revisions = @post.original.revisions
    

    【讨论】:

    • 这很棒!非常感谢。我很好奇我会如何过滤掉这样的修订。您对我如何做到这一点有任何见解吗?
    • 你想如何过滤它们?无论如何,您可以照常使用scopes,例如:@post.original.revisions.your_current_scope
    • 例如,在创建新帖子时,您可以选择使其成为另一个帖子的修订版。但是,目前它将显示所有帖子,其中包括其他人的修订帖子。我只想显示有修订的帖子,但不是修订本身。
    猜你喜欢
    • 2015-09-25
    • 2020-04-06
    • 2013-05-24
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多