如果我将输入框留空。我每次都收到这个错误。我不希望它在空白时创造新记录。如果没有,我希望它创造新的记录。
这个输入框是嵌套的,控制器的代码是这样写的,以免出错
def create
# Check if there is any contact info added
if params[:girl][:contact_attributes][:mail].empty?
params[:girl].delete(:contact_attributes)
end
@girl = Girl.new(params[:girl])
respond_to do |format|
if @girl.save
format.html { redirect_to @girl, notice: 'Girl was successfully created.' }
format.json { render json: @girl, status: :created, location: @girl }
else
format.html { render action: "new" }
format.json { render json: @girl.errors, status: :unprocessable_entity }
end
end
end
视图是这样的
<%= form_for(@girl) do |f| %>
....
<div class="field">
<%= f.label :mail %><br />
<%= f.fields_for :contact_attributes, @girl.contact do |contact| %>
<%= contact.text_field :mail %>
<% end %>
</div>
....
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我的模型
class Girl < ActiveRecord::Base
has_many :users
has_one :contact
accepts_nested_attributes_for :contact
attr_accessible :id, :name_en, :name_ja, :gender_id, :contact_attributes, :photo, :tag_list
searchable do
text :name_en, :name_ja
text :contact do
contact.mail
end
end
has_attached_file :photo,
:styles => {
:thumb=> "100x100>",
:small => "400x400>" }
acts_as_taggable_on :tags
acts_as_commentable
end