我有一个模型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
选择而不会被拒绝,所以如何解决此问题
答案 0 :(得分:0)
您只需将validates :language_name, presence: true
添加到ProfileLanguage
模型即可。这样可以确保在没有ProfileLanguage
的情况下不会保留:language_name
的记录。