如何让rails3 在新操作的表单字段中显示初始值?

发布于 2024-11-15 10:50:54 字数 782 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱给你人给你 2024-11-22 10:50:54

在您的控制器中尝试类似的操作:

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
  ...

即使记录未保存,表单应该具有初始值。

Try something like this in your controller:

def new
  last_post = Post.last
  @post = Post.new
  @post.title = last_post.title
  @post.summary = last_post.summary
  ...
end

... then in your view you should have something like:

form_for @post do |form|
  form.text_field :title
  form.text_area :summary
  ...

The form should have the initial values even if the record is unsaved.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文