2015-01-05 36 views
0

我有接受ProfileLanguage嵌套的属性模型Profile 4 reject_if:的Rails在nested_attributes

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选择不会被拒绝,所以如何解决此问题

+0

看一看''select'](http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select)助手的选项'include_blank'。 – vee

回答

0

您可以将validates :language_name, presence: true添加到您的ProfileLanguage型号中。这将确保没有:language_name没有记录ProfileLanguage将被保留。

相关问题