Rested 4 reject_if在nested_attributes中

时间:2015-01-05 21:33:45

标签: ruby-on-rails ruby ruby-on-rails-4 nested-attributes

我有一个模型Profile,它接受​​ProfileLanguage作为嵌套属性:

class Profile < ActiveRecord::Base
    belongs_to :user

    has_many :profile_languages, dependent: :destroy
    accepts_nested_attributes_for :profile_languages, reject_if: proc { |a| a[:language_name].blank? }
end

class ProfileLanguage < ActiveRecord::Base
    belongs_to :profile
    validates_inclusion_of :proficiency, :in => %w( 1 2 3 4 5 ), :message => "Veuillez choisir un niveau valide"
end

以下是我使用的表格:

<%= f.fields_for :profile_languages do |pl| %>
        <div class="plform-group">
            <div class="form-planguage-half">
              <%= pl.text_field :language_name, class: 'form-control form-two-half'  %>
            </div>
            <div class="form-planguage-half-last">
              <%= pl.select(:proficiency, [
                      ["Débutant", 1], 
                      ["Intermédiaire", 2], 
                      ["Courant", 3], 
                      ["Bilingue", 4], 
                      ["Natif", 5]], 
                      {}, {class: "form-control form-two-half"}) %>
            </div>
        </div>
<% end %>

问题是当language_name的字段为空时,由于proficiency选择而不会被拒绝,所以如何解决此问题

1 个答案:

答案 0 :(得分:0)

您只需将validates :language_name, presence: true添加到ProfileLanguage模型即可。这样可以确保在没有ProfileLanguage的情况下不会保留:language_name的记录。