我是新手。我已阅读 API 文档。但还是不明白 form_for 是如何工作的。
首先,来自 Ruby on Rails 教程,跟随按钮的表单:
<%= form_for(current_user.relationships.build(followed_id: @user.id)) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
我明白
current_user.relationships.build(followed_id: @user.id)
意味着一个新的记录。但是为什么我们不能只提交和触发 Controller 来保存没有 hidden_field 的记录呢?为什么我们仍然需要将 follow_id 发布到 Controller ?其次,在hidden_field中,
:followed_id
有什么作用?方法?我相信这是一个符号,即它仅等于“followed_id”而不是 id 变量。如果这只是输入字段的名称,那么它的值是什么?三、如何
form_for
知道提交应该发送到哪里?哪个 Controller 和 Action form_for
会发到?四、怎么办
params
与 form_for
一起工作?在此跟随按钮案例中,params[:relationship][:followed_id]
将返回 @user.id
在 Controller 中。它怎么知道第一个哈希属性是:relationship
?我们都没有提到form_for :relationship
也不是 form_for @relationship
.我知道这些问题可能非常愚蠢,但我真的被困住了。任何帮助将不胜感激。
最佳答案
我没有做那个教程,所以如果我不直接回答你的问题,请介意我。
看看rails guide about form helpers它详细解释了你的问题,可能比我更清楚。form_for(path/to/your/controller/action)
是一种辅助方法,用于创建带有 POST 或 GET 请求的 url 路径的 HTML 表单元素。助手根据您在 Controller 操作中要求执行的操作知道它应该是新记录还是更新记录。
例如
在您的 Controller 中
def new
@my_instance_variable = Myobject.new
end
在你看来 new.html.erb
<%= form_for @my_instance_variable do |f| %>
...
<% end %>
在你的情况下,逻辑是直接写在助手中的,你也可以直接写
<%= form_for Myobject.new %>
两者都会产生以下 html
<form action="/myobjects/new" method="post">
# in this case rails knows its a `POST` request because the route new action
# is by default a POST request. You can check these routes and their request
# by using `rake routes` in terminal.
然后是
hidden_field
是另一个包含值的助手,在您的情况下是 @user.id
将作为参数传递,然后保存为给定对象的创建或更新操作。它没有在隐藏字段标记中添加值的原因是因为您已经有一个知道用户 ID 的模型关联,因为表单链接使用带有用户 ID 的构建方法。最后一部分你需要了解form_for链接逻辑
current_user.relationships
# implies the association of the current_user has many relationships
current_user.relationships.build
# .build is a method to populate a new object that can be save as a new record
# means you will create a new relationship record by populating the user_id
# column with the current_user.id and the followed_id with the target @user.id
关于ruby-on-rails - form_for 如何在 Ruby on Rails 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20500511/