2011-01-10 46 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? }