新手问题 神奇的 form_for

xiaoronglv · 2012年07月24日 · 最后由 runup 回复于 2016年09月25日 · 2238 次阅读

如果是新资源,form_for(@post) 就会调用 create action,创建新资源。

如果是已存在的资源,form_for(@post) 就会调用 update,更新资源。

虽然两者写法一样,但是聪明的 rails 会根据 record.new_record?来判断,选择合适的 action。

## Creating a new article
# long-style:
form_for(@article, :url=> articles_path)
# same thing, short-style (record identification gets used):
form_for(@article)

## Editing an existing article
# long-style:
form_for(@article, :url=> article_path(@article), :html=> { :method=> "put"})
# short-style:
form_for(@article)

魔法!

使用 form_for(@post) 和 form_for(:post) 有什么区别么?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号