我有一个用于 Rails 表单的多选输入字段。除非用户提交模型中的验证器不接受的值,否则它可以完美运行。当页面重新呈现并显示错误消息时,表单字段从多选字段变为文本字段。我认为问题在于rails出于某种原因改变了css类。这是为表单加载实例变量的控制器:
def edit
@skills = Skill.all.collect {|skill| skill.label}
@profile = current_user.profile
end
这是表格:
<%= simple_form_for(@profile, :html => { :method => :put }) do |f| %>
<%= f.error_notification %>
<%= f.input :tag_list, collection: @skills,
input_html: {class: 'chosen-select', multiple: true,
style: 'width: 390px; height: 40px; border-radius: 5px;'},
placeholder: 'Tags (seperated by commas)', label: "-" %> <br />
<%= f.submit "Save" %>
<% end %>
这是更新控制器:
def update
@profile = current_user.profile
begin
if @profile.update_attributes!(profile_params)
flash[:notice] = "Successfully updated profile."
redirect_to profile_path(current_user.profile_name)
else
render :action => 'edit'
end
rescue
render :action => 'edit'
end
end
第一次重新设计时,该表单可以完美运行。为该字段生成的 html 如下所示:
<div class="input select optional profile_tag_list">
<label class="select optional" for="profile_tag_list">-</label>
<input name="profile[tag_list][]" type="hidden" value="" />
<select class="select optional chosen-select" id="profile_tag_list"
multiple="multiple" name="profile[tag_list][]"
placeholder="Tags (seperated by commas)"
style="width: 390px; height: 40px; border-radius: 5px;">
<option value="Finance">Finance</option>
<option value="PHP">PHP</option>
<option value="python">python</option>
</select>
</div>
但是当它在更新操作失败后渲染时,html是这样的:
<div class="input string optional profile_tag_list field_with_errors">
<label class="string optional" for="profile_tag_list">-</label>
<input class="string optional chosen-select" id="profile_tag_list"
multiple="multiple" name="profile[tag_list][]"
placeholder="Tags (seperated by commas)"
style="width: 390px; height: 40px; border-radius: 5px;" type="text"
value="PHP" />
<span class="error">Please only submit skills from the list.</span>
</div>
如何让表单在重新呈现时仍显示选择字段?谢谢。