Rails 5:form_for 对比 form_with
Rails 5: form_for vs form_with
Rails 5引入了新的表单辅助方法form_with
.
它与form_for
有何不同,什么时候更适合使用?
这实际上是在为 rails 5.1 做准备,其中只应使用 form_with
。它旨在替代 form_for
和 form_tag
这两种方法。
form_for
and form_tag
in Rails were very similar, both allowed you to create a form tag but the first one uses model’s attributes to build create or update form, while the second one simply creates an HTML form tag with the passed URL as action.
使用form_with(更新)
form_with
是街区的新生。 form_for
和 form_tag
现在(基本上)已过时。
为什么有变化?
原因包含在 Kasper Timm Hansen's pull request - I cannot say it better than what is stated already in the pull request itself 中(请参阅拉取请求的 link)。
拉取请求中的直接引用:
form_tag and form_for serve very similar use cases. This
PR unifies that usage such that form_with can output just
the opening form tag akin to form_tag and can just work with
a url, for instance.
这意味着如果您没有模型,则无需使用 form_tag。您可以使用 form_with
助手,它仍然可以处理 URL。
注意回复:Ids 和 类: Ruby 5.1 版本的 form_with
,默认情况下不附加 class 或表格的 id。但是,对于 Rails 5.2 及更高版本,form_with
将根据模型自动生成 ID(如果存在)— 基本上与 form_for
相同的 ID 行为,因此您无需手动指定它们了。 (source)
现有答案很棒。我还发现有帮助的是前几段 here。基本上:
form_tag
and form_for
are soft deprecated and they will be replaced by form_with
in the future.
- DHH 的提议:https://github.com/rails/rails/issues/25197
- 拉取请求:https://github.com/rails/rails/pull/26976/files(我没读过,但可能有用)
Rails 5引入了新的表单辅助方法form_with
.
它与form_for
有何不同,什么时候更适合使用?
这实际上是在为 rails 5.1 做准备,其中只应使用 form_with
。它旨在替代 form_for
和 form_tag
这两种方法。
form_for
andform_tag
in Rails were very similar, both allowed you to create a form tag but the first one uses model’s attributes to build create or update form, while the second one simply creates an HTML form tag with the passed URL as action.
使用form_with(更新)
form_with
是街区的新生。 form_for
和 form_tag
现在(基本上)已过时。
为什么有变化?
原因包含在 Kasper Timm Hansen's pull request - I cannot say it better than what is stated already in the pull request itself 中(请参阅拉取请求的 link)。
拉取请求中的直接引用:
form_tag and form_for serve very similar use cases. This PR unifies that usage such that form_with can output just the opening form tag akin to form_tag and can just work with a url, for instance.
这意味着如果您没有模型,则无需使用 form_tag。您可以使用 form_with
助手,它仍然可以处理 URL。
注意回复:Ids 和 类: Ruby 5.1 版本的 form_with
,默认情况下不附加 class 或表格的 id。但是,对于 Rails 5.2 及更高版本,form_with
将根据模型自动生成 ID(如果存在)— 基本上与 form_for
相同的 ID 行为,因此您无需手动指定它们了。 (source)
现有答案很棒。我还发现有帮助的是前几段 here。基本上:
form_tag
andform_for
are soft deprecated and they will be replaced byform_with
in the future.
- DHH 的提议:https://github.com/rails/rails/issues/25197
- 拉取请求:https://github.com/rails/rails/pull/26976/files(我没读过,但可能有用)