Rails、has_one、build_#{association}、accepts_nested_attributes_for
我正在尝试开发一个具有版本历史记录的维基。
我的计划是:每次我编辑维基内容时,它都应该保存为新内容。
现在,我有两个模型,Wiki 和 WikiContent,以及它们内部的以下代码:
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 模型有一个字段 current_id,用于知道哪个内容是当前内容。
在 Wiki 控制器中我运行
def new
@wiki.build_current_wiki
end
def create
@wiki=Wiki.new(params[:wiki])
@wiki.save
@[email protected]_wiki.id
end
但是每当我尝试运行时:
def edit
@wiki.build_new_content
end
它都会将 NULL 分配给 current_wiki.wiki_id 。
我该如何解决这个问题? 或者还有其他方法可以让它发挥作用吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为如果您稍微重新设计模型,您可能会更轻松。
Wiki 有很多修订版,但只有一个最新修订版。现在,您不必管理
current_id
,因为latest_revision
关联会为您处理此事。I think you may have an easier time if you re-design your models a bit.
A Wiki has many revisions, but only has one latest revision. Now you don't have to manage
current_id
, since thelatest_revision
association will take care of that for you.