我试图在一个表单中创建多个项目(每个项目都有一个名称值和一个内容值)。我拥有的代码正在运行,但我无法弄清楚如何忽略空白的项目。下面的代码:在Ruby on Rails中忽略所有空白字段的模型
#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个项目,即使其他项目保留空白。
我确信有一个简单的解决方案,但我一直在修补几个小时没有用。任何帮助表示赞赏!
您应该在控制器级别过滤参数。 – apneadiving 2011-01-10 23:21:13
@apneadiving - 你能更具体吗?我不确定具体如何工作。谢谢! – aguynamedloren 2011-01-10 23:28:14
你应该遵循cam的编码方式,但你应该使用params散列。我同意看看,但请给我一个参数样本(看看你的日志) – apneadiving 2011-01-10 23:43:17