1

本质上:

  • 我想将title修订的标题设置为它是修订的帖子的标题。
  • 如果新帖子不是修订版(或),我想将 设置revision_ididis_revision = false

到目前为止,我在这方面遇到了很多麻烦。任何帮助表示赞赏。

post.rb

class Post < ActiveRecord::Base

has_many :revisions, class_name: "Post", foreign_key: "revision_id"
belongs_to :revision, class_name: "Post"

#...

before_save :post_title

def post_title
  if :is_revision == false
    @revision_id = @post_id
  elsif :is_revision == true
    :revision_id != :post_id
    @title = @revision.title
  end
end

#...

end

更新

我现在可以通过控制器来完成这项工作。我是否仍应致力于使这项工作在模型中进行?相同的代码在创建和更新操作下。

post_controller.rb

def create
    @post = current_user.posts.new(params[:post])

    if @post.save
    if @post.is_revision == false
      @post.revision_id = @post.id
      @post.save
    elsif @post.is_revision == true
      @post.title = @post.revision.title
      @post.save
    end
    end
end
4

1 回答 1

0

我不太明白你的逻辑,也许你应该告诉我们一些背景。

否则,您是否只是尝试:

class Post < ActiveRecord::Base

has_many :revisions, class_name: "Post", foreign_key: "revision_id"
belongs_to :revision, class_name: "Post"

#...

before_save :set_title_to_revision_title, :if => :is_revision?

# Need to be called after the save because post.id will not be available on the create
after_save :update_revision_id_to_id, :unless => :is_revision?

def is_revision?
  @is_revision
end

def set_title_to_revision_title
  @title = @revision.title 
end

def update_revision_id_to_id
  # just make a quick call to update it i
  update_attribute :revision_id, @id
end

#...

end
于 2013-06-28T16:20:47.353 回答