我使用formtastic這樣保存未通過驗證的子字段?
class Court < ActiveRecord::Base
belongs_to :tournament
end
class Tournament < ActiveRecord::Base
has_many :courts, :dependent => :destroy
accepts_nested_attributes_for :courts, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
validates :name, :presence => true, :length => { :maximum => 100 }
end
和所有工作正常,但在比賽中失敗的驗證,形成創建不保留一個失敗的窗體上法庭。
這裏是我的控制器
def new
@tournament = Tournament.new
1.times do
@tournament.courts.build
end
def create
@tournament = Tournament.new(params[:tournament])
我認爲我可以做這樣的事情,但創建沒有去
if params[:tournament][:courts_attributes]
params[:tournament][:courts_attributes].each { |attribute|
@tournament.courts.build(attribute)
}
end
<%= semantic_form_for @tournament do |f| %>
<%= f.inputs do %>
<%= f.input :number_courts, :hint => "How many courts are available?" %>
<%= f.semantic_fields_for :courts do |builder| %>
<%= render :partial => "court_fields", :locals => { :f => builder } %>
<span class="links">
<%= link_to_add_fields "Add More Court", f, :courts %>
</span>
<% end %>
部分
<div class="nested_fields">
<%= f.input :name %>
<%= f.input :address %>
<%= f.input :city %>
<%= f.input :state %>
<%= f.input :zip %>
<%= f.input :phone %>
<%= f.input :contact_name %>
<%= link_to_remove_fields "Remove Court", f %>
</div>
UPDATE ---
他再是我創造的動作
def create
@tournament = Tournament.new(params[:tournament])
respond_to do |format|
if @tournament.save
format.html { redirect_to @tournament, notice: 'Tournament was successfully created.' }
format.json { render json: @tournament, status: :created, location: @tournament }
else
format.html { render action: "new" }
end
這裏也有公正的情況下PARAMS,這將有助於
Processing by TournamentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xv+p7QdpkJdEUaTGqrKue63869hlwh3Zv1xvkO5qx6A=", "tournament"=>{"name"=>"", "sport_id"=>"1", "entry_fee"=>"", "start_date"=>"", "end_date"=>"", "number_courts"=>"", "courts_attributes"=>{"0"=>{"name"=>"hello", "_destroy"=>"false"}, "1318725283928"=>{"name"=>"asdfsadfas", "_destroy"=>"false"}, "1318725286739"=>{"name"=>"asdfasdfa", "_destroy"=>"false"}}, "available_times"=>"", "available_end_times"=>"", "min_games"=>"", "time_allowed"=>"1:15", "number_teams_per_bracket"=>"1", "gender_id"=>"1", "entry_deadline"=>"", "age_limit"=>"", "rules"=>"", "coach_meeting"=>"0", "meeting_location"=>"", "meeting_date"=>"", "future_tournament"=>"0", "private_service"=>"0", "add_blog"=>"0"}, "commit"=>"Create Tournament"}
如何在驗證失敗保存數據的任何想法
你可以請張貼你的表格嗎?另外,'1.times' – bricker
@bricker - 對不起1次....我從25次改變了它,忘了取消循環..現在發佈表格 – Trace
是的,我認爲是這樣,當我第一次看時,它顯得很愚蠢它。 – bricker