新手问题 怎么搞清楚 FormHelpers 里面的方法对应产生的 HTML attributes 在 Rails 里的作用和相互关系?

stardiviner · 2016年02月18日 · 最后由 fighterleslie 回复于 2016年02月19日 · 2237 次阅读

比如这些例子:

text_field(:post, :title, size: 20)
  # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />

  text_field(:post, :title, class: "create_input")
  # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />

  text_field(:session, :user, onchange: "if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }")
  # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange="if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }"/>

  text_field(:snippet, :code, size: 20, class: 'code_input')
  # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" />

我搞不明白哪些是相对应的,每个都是什么作用。 如果有这方面的文档最好。最好能解释下这些属性为什么会这样。

-- EDIT -- 比如 这里 id 和 name 什么作用?有什么差别? 我发现 text_field(:post, :title, size: 20) 会创建 id, name 这些 attributes,不 像 class 是在 text_field(:post, :title, class: "create_input") 中被赋予的。

这些 HTML attributes 似乎都是用来被从 View 获取,然后被赋予给 Controller,然后传输给 Model,谁能给出几个例子说明这里面是怎么传递的?

好像和 assets pipeline 有关。像是 data-* HTML attributes.

-- EDIT 2 -- 看了 1 楼的连接 API 文档显示的 source code:

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 188
def text_field_tag(name, value = nil, options = {})
  tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
end

后明白这些 attributes 是如何赋值以及输出成 HTML 的了。 但是还是没明白他们的作用和如何传递给 controller,model 的。

以 text_field 为例,读 text_field_tag 的 API 文档

  • :disabled - If set to true, the user will not be able to use this input.
  • :size - The number of visible characters that will fit in the input.
  • :maxlength - The maximum number of characters that the browser will allow the user to enter.
  • :placeholder - The text contained in the field by default which is removed when the field receives focus.
  • Any other key creates standard HTML attributes for the tag.

所以 data-*这样的 HTML 属性其实不属于 Rails 知识范围,Rails 只是帮你原样输出了。

#1 楼 @ericguo 看了你的 API 连接后,明白 id 和 name 这些 attributes 是怎么来的了。但是还是没搞明白作用和关系。

#2 楼 @stardiviner HTML 属于 Web 前端的知识,找本前端的书看看就明白了,其实挺简单的。

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