2011-01-10 81 views
1

我试图在一个表单中创建多个项目(每个项目都有一个名称值和一个内容值)。我拥有的代码正在运行,但我无法弄清楚如何忽略空白的项目。下面的代码:在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个项目,即使其他项目保留空白。

我确信有一个简单的解决方案,但我一直在修补几个小时没有用。任何帮助表示赞赏!

+0

您应该在控制器级别过滤参数。 – apneadiving 2011-01-10 23:21:13

+0

@apneadiving - 你能更具体吗?我不确定具体如何工作。谢谢! – aguynamedloren 2011-01-10 23:28:14

+0

你应该遵循cam的编码方式,但你应该使用params散列。我同意看看,但请给我一个参数样本(看看你的日志) – apneadiving 2011-01-10 23:43:17

回答

1

我应该这样做:

class Item 
    def empty? 
    attributes.values.compact.empty? 
    end 
end 

# in ItemsController 
if @items.reject(&:empty?).all(&:save) 

一对夫妇的注意事项:

  1. 您正在使用save!,但您可能需要save。如果其中一项无效,save!会引发异常,您只会看到一个错误页面,而不是您的new模板。
  2. 我将each替换为alleach不会做你想要的 - 这是返回true当且仅当所有的项目验证和保存。 all就是这样。
1

我不知道这是最好的解决办法,但也许你可以这样做:

@items.reject! { |item| item.attributes.values.compact.empty? }