rails, has_one, build_#{association}, accepts_nested_attributes_for
-
05-07-2019 - |
Question
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
@wiki.current_id=@wiki.current_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?
Solution
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow