سؤال

HTML views like this:

□ホーチミン □ハノイ □フエ □ホイアン □その他

I got a problem, the validate is you must select at least one checkbox, so if no checkbox be checked it will show an error

When I select some checkboxes, my view look fine and no problem

☑ホーチミン ☑ハノイ □フエ □ホイアン □その他

But when I don't check any checkbox, my view will auto creates linebreak like this:

□
ホーチミン 
□
ハノイ 
□
フエ 
□
ホイアン 
□
その他
都市を選択してください

contact.rb:

validate :validate_city_ids
  serialize :city_ids

  def validate_city_ids
    unless city_ids
      errors.add(:city_ids, "都市を選択してください")
    end
  end

In this file above, if I remove line: errors.add(:city_ids, "都市を選択してください") of course if won't show error, in this statement, it don't auto creates linebreaks

My View looks like this:

<td>
        <%= f.check_box :city_ids, {multiple: true}, "1", nil %> <%= f.label :"ホーチミン" %> &nbsp;
        <%= f.check_box :city_ids, {multiple: true}, "2", nil %> <%= f.label :"ハノイ" %> &nbsp;
        <%= f.check_box :city_ids, {multiple: true}, "3", nil %> <%= f.label :"フエ" %> &nbsp;
        <%= f.check_box :city_ids, {multiple: true}, "5", nil %> <%= f.label :"ホイアン" %> &nbsp;
        <%= f.check_box :city_ids, {multiple: true}, "7", nil %> <%= f.label :"ニャチャン" %>
        <br/>
        <%= f.check_box :city_ids, {multiple: true}, "6", nil %> <%= f.label :"ムイネー" %> &nbsp;
        <%= f.check_box :city_ids, {multiple: true}, "11", nil %> <%= f.label :"その他" %> &nbsp;
        <br/>
        <% if @contact.errors[:city_ids].any? %>
          <span class="error-explain">
            <%= @contact.errors[:city_ids].first %>
          </span>
        <% end %>
      </td>
هل كانت مفيدة؟

المحلول

After inspecting the whole thing myself, this is the problem:

Rails puts the "fields_with_error" div around the checkbox. There are several possible ways to solve this, the most straightforward would be applying a css rule to "fields_with_error"

.field_with_errors {
    display: inline;
}

OR change the default behavior by adding this to config/application.rb

config.action_view.field_error_proc = Proc.new { |html_tag, instance| 
  "#{html_tag}".html_safe 
}

This needs an application restart to take effect! It will wrap the fields_with_error div around label.

In any case change error-explain span to

<div class="error-explain">
  <%= @contact.errors[:email].first %>
</div>

Have fun ;)

NOTE: I used the following markup:

<label for="contact_ホーチミン">
  <%= f.check_box :city_ids, {multiple: true}, "1", nil %> ホーチミン &nbsp;
</label>
<label for="contact_ハノイ">
  <%= f.check_box :city_ids, {multiple: true}, "2", nil %> ハノイ &nbsp;
</label>
...
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top