如何让rails3 在新操作的表单字段中显示初始值?
Rails3 form_for 视图助手在编辑时显示当前值。
我想在创建时用一些初始值填充模型。每次初始值都不同,但实际上是从最后存储的记录中复制一些值。
当我这样做并使用 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)
end
Ruby 显然将第一种形式解释为局部变量的赋值。
The Rails3 form_for view helper displays current values on edit.
I would like to populate the model with some initial values on create. Not the same initial value every time, but actually copy some of the values from the last record stored.
When I do this, and use the form_for helper to construct the form, none of the values appear.
It looks like form_for does not emit the value attributes for input fields of a model not yet saved? But I wouldn't save the newly created model before displaying the form because: 1. it would not validate, 2. that complicates the semantics of canceling, 3. navigating away from the form would leave an unintentionally saved record.
How can I get a form rendered from the new action to display some dynamic defaults?
Seriously. I've been reading all day without an answer. This seems like there ought to be an easy solution that I'm missing.
The problem came from the initialization code in the model. The controller had
def new
@post = Post.new
@post.initFromLast
end
The model had
def initFromLast
last_post = Post.last
title = last_post.title
summary = last_post.summary
end
The model needed
def initFromLast
last_post = Post.last
write_attribute(:title, last_post.title)
write_attribute(:summary, last_post.summary)
end
Ruby apparently interpreted the first form as assignments to local variables.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的控制器中尝试类似的操作:
...然后在您看来,您应该具有类似以下内容:
即使记录未保存,表单应该具有初始值。
Try something like this in your controller:
... then in your view you should have something like:
The form should have the initial values even if the record is unsaved.