我试图在一个表单中创建多个项目(每个项目都有一个名称值和一个内容值)。我的代码正在运行,但我无法弄清楚如何忽略空白的项目。这是代码:
#item.rb
class Item < ActiveRecord::Base
attr_accessible :name, :content
validates_presence_of :name, :content
end
#items_controller.rb
class ItemsController < ApplicationController
def new
@items = Array.new(3){ Item.new }
end
def create
@items = params[:items].values.collect{|item|Item.new(item)}
if @items.each(&:save!)
flash[:notice] = "Successfully created item."
redirect_to root_url
else
render :action => 'new'
end
end
#new.html.erb
<% form_tag :action => 'create' do %>
<%@items.each_with_index do |item, index| %>
<% fields_for "items[#{index}]", item do |f| %>
<p>
Name: <%= f.text_field :name %>
Content: <%= f.text_field :content %>
</p>
<% end %>
<% end %>
<%= submit_tag %>
<% end %>
此代码适用于所有项目的所有字段都填写在表单中,但如果任何字段留空(由于验证),则会失败。目标是可以保存1或2个项目,即使其他项目留空。
我确信这有一个简单的解决方案,但我一直在修补几个小时但没有用。任何帮助表示赞赏!
答案 0 :(得分:1)
我不确定这是最好的解决方案,但也许你可以这样做:
@items.reject! { |item| item.attributes.values.compact.empty? }
答案 1 :(得分:1)
我会这样做:
class Item
def empty?
attributes.values.compact.empty?
end
end
# in ItemsController
if @items.reject(&:empty?).all(&:save)
一对夫妇注意到:
save!
,但您可能需要save
。如果其中一个项目无效,save!
会引发异常,您只会看到错误页面而不是new
模板。each
替换为all
。 each
不会按照您的意图执行 - 当且仅当所有项目都经过验证和保存时,才会返回true
。 all
就是这么做的。