我試圖在一個表單中創建多個項目(每個項目都有一個名稱值和一個內容值)。我擁有的代碼正在運行,但我無法弄清楚如何忽略空白的項目。下面的代碼:在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