新手问题 神奇的 form_for

xiaoronglv · July 24, 2012 · Last by runup replied at September 25, 2016 · 2255 hits

如果是新资源,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) 有什么区别么?

You need to Sign in before reply, if you don't have an account, please Sign up first.