views:

695

answers:

1

i am trying to develop a wiki with version history.

my plan is: each time i edit a wiki content, it should get saved as a new one.

for now, i have two models, Wiki, and WikiContent, and following code inside them:

class Wiki < ActiveRecord::Base

  has_many :wiki_contents 

  has_one :current_wiki, :class_name => "WikiContent"
  accepts_nested_attributes_for :current_wiki

  has_one :new_content, :class_name => "WikiContent"
  accepts_nested_attributes_for :new_content

end
class WikiContent < ActiveRecord::Base
  belongs_to :wiki
end

Wiki model has a field current_id, to know which content is the current one.

in Wiki controller i run

def new
  @wiki.build_current_wiki
end
def create
  @wiki=Wiki.new(params[:wiki])
  @wiki.save
  @[email protected]_wiki.id
end

But whenever i try to run:

def edit
  @wiki.build_new_content
end

it assigns NULL to current_wiki.wiki_id.

how can i fix that? or is there another way to get this to work?

+2  A: 

I think you may have an easier time if you re-design your models a bit.

class Wiki < ActiveRecord::Base
  has_many :revisions 

  has_one :latest_revision, :class_name => "Revision", :order => 'updated_at desc', :limit => 1
  accepts_nested_attributes_for :revisions
end

class Revision < ActiveRecord::Base
  belongs_to :wiki
end


# new Wiki page, first revision
def new
  @wiki = Wiki.new
  @revision = @wiki.revisions.build
end

def create
  @wiki=Wiki.new(params[:wiki])
  @wiki.save
end

# adding a Revision to a Wiki page
def edit
  @wiki = Wiki.find(params[:id])
  @revision = @wiki.revisions.build # creating a new revision on edit
end

def update
  @wiki=Wiki.new(params[:wiki])
  @wiki.save
end

def show
  @wiki = Wiki.find(params[:id])
  @revision = @wiki.latest_revision
end

A Wiki has many revisions, but only has one latest revision. Now you don't have to manage current_id, since the latest_revision association will take care of that for you.

Jonathan Julian
thanks, shown code is not working, as 'build' syntax for has_many is bit different than for has_one ([email protected]_revision has to be @wiki.revisions.build), but the idea to switch to has_many and use "updated_at desc' moved me few steps forward. i'll keep the current_id though, it makes some queries lighter.
Pavel K.
I've updated the build syntax. Glad I could help.
Jonathan Julian