hyp*_*jas 38 ruby ruby-on-rails form-for ruby-on-rails-3
我有这个form_for:
<%= form_for [post, Comment.new,], :remote => true do |f| %>
<%= f.text_area :content, :cols =>10, :rows => 1%>
<% end %>
<%= f.submit :class => "input_comment" %>
Run Code Online (Sandbox Code Playgroud)
那会生成下一个代码html:
<form method="post" id="new_comment" data-remote="true" class="new_comment"
action="/post/4efcda9e1d41c82486000077/comments" accept-charset="UTF-8"><div
style="margin:0;padding:0;display:inline"><input type="hidden" value="?" name="utf8">
<input type="hidden" value="ctVfDF/O4FIR91I7bC5MVezQmutOCkX3dcXe73uNPZY=" name="authenticity_token">
<textarea rows="1" name="comment[content]" id="comment_content" cols="10"></textarea>
<input type="submit" value="Create Comment" name="commit" class="input_comment">
</form>
Run Code Online (Sandbox Code Playgroud)
如果我在同一页面中有多个表单,则不是具有相同ID的html有效.
在同一页面中有这么多表单是无效的HTML.
如何通过rails 3.1中的form_for方法助手更改id autogenerate?
Bat*_*ins 76
添加到miked所说的,为帖子制作唯一表单id的最简单方法是在id属性中使用post的id号,如下所示:
<%= form_for [post, Comment.new,], :remote => true, :html => { :id => "new_comment_on_#{post.id}" } do |f| %>
Run Code Online (Sandbox Code Playgroud)
Sub*_*ree 18
我认为这个:namespace
选项正是你要找的.
它将名称附加到表单的id 以及所有输入和标签字段.
例如
<%= form_for [post, Comment.new,], namespace: 'NAMESPACE', :remote => true do |f| %>
<%= f.text_area :content, :cols =>10, :rows => 1%>
<% end %>
Run Code Online (Sandbox Code Playgroud)
会产生:
表格id = NAMESPACE_new_comment
Textarea id = NAMESPACE_comment_content
来自文档:
:namespace - 表单的命名空间,用于确保表单元素上id属性的唯一性.namespace属性将在生成的HTML id上以下划线为前缀
mik*_*ked 15
您应该能够将表单的id设置为您想要的任何内容.就像是:
<%= form_for @object, :html=> {:id => 'custom_form_id'} do |f| %>
Run Code Online (Sandbox Code Playgroud)