新手问题 这种表单有哪些写法?

xiaoronglv · 2012年08月08日 · 最后由 fenprace 回复于 2012年08月08日 · 2513 次阅读

在看 terry 的 railscast-china 视频时碰到一个关于表单的问题,这一集是创建一个 blog(博客) web app。

http://railscasts-china.com/episodes/1-rails-tutorial

routes.rb resources :posts do resources :comments end

post.rb class Post < ActiveRecord::Base attr_accessible :content, :title validates :content, :title, :presence => true validates :title, :uniqueness => true has_many :comments end

comment.rb class Comment < ActiveRecord::Base attr_accessible :content, :post_id validates :content, :presence => true belongs_to :post end


在 post(博文)的 show 页面,构建一个表单,可以针对每篇 post(博文)发表 comments(评论)。

terry 在视频中的表单样式的写法,完全看不懂,各位能指点一下吗?

1 url 呢?

  1. method 呢?
  2. 这里的中括号是啥意思?如果使用 url_helper,这个表单的代码该如何写呢?

万分感谢

<%= form_for [@post, Comment.new] do |f|%> …… …… <%= end %>

共收到 7 条回复

[@post, Comment.new] 表示一个数组

[@post, Comment.new] 相当于生成这样一个 url :

POST /posts/1/comments/

因为在 routes 里:

resources :posts do
  resources :comments
end

comments 是嵌套在 posts 里的。

It mentions the following:

<%= form_for([@post, @post.comments.build]) do |f| %>

Why should we insert TWO arguments?

It's because comment is setup as a resource nested within post.

The form_for needs to generate the right combination of url and http verb, and this depends on whether or not the comment is a new record. The form_for helper is designed to allow the same form to be used both for the new and edit views.

Passing an array tells form_for that it's a nested resource.

In this case, @post.comments.build will be a new record, it won't have an id until it's saved. Let's say that the id of @post is 42. Then the form should be set up to send a post request using the uri path 'posts/42/comments

If it was the edit case then the comment would have an id, say 432, and you'd use something like

form_for @post, @comment

where the edit action in the controller set both instance variables, and the form would send a put request to the url 'post/42/comments/432'

If you just gave form_for the single value @post.comments.build then it assumes that the comment resources isn't nested and it would post to the uri path 'comments' but the way the routes are specified this isn't going to work.

感谢各位的讲解,以及详细的文档。

如果这个表单用 url_helper 的方式撰写,会是什么样子?

<%= form_for @post.comments.new do |f| %>
  ……
<% end %>
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册