Rails3 form_for视图助手在编辑时显示当前值。
我想用create的一些初始值填充模型。每次都不是相同的初始值,但实际上是从上次存储的记录中复制一些值。
当我这样做并使用form_for助手构造表单时,所有的值都不会出现。
看起来form_for没有为尚未保存的模型的输入字段发出值属性?但是在显示表单之前,我不会保存新创建的模型,因为: 1.它不会验证,2.这会使取消的语义复杂化,3.离开表单导航会留下意外保存的记录。
如何使新操作呈现的表单显示一些动态默认值?
我是认真的。我一整天都在看书,没有回答。这似乎应该有一个简单的解决方案,我错过了。
问题来自于模型中的初始化代码。调度员
def new
  @post = Post.new
  @post.initFromLast
end模型
def initFromLast
  last_post = Post.last
  title = last_post.title
  summary = last_post.summary
end所需的模型
def initFromLast
  last_post = Post.last
  write_attribute(:title, last_post.title)
  write_attribute(:summary, last_post.summary)
endRuby显然将第一种形式解释为对局部变量的赋值。
发布于 2011-06-14 20:34:20
在你的控制器里试试这样的东西:
def new
  last_post = Post.last
  @post = Post.new
  @post.title = last_post.title
  @post.summary = last_post.summary
  ...
end..。那么在你看来,你应该有这样的东西:
form_for @post do |form|
  form.text_field :title
  form.text_area :summary
  ...即使记录未保存,表单也应该具有初始值。
https://stackoverflow.com/questions/6349679
复制相似问题