How can I stop a form repeating using fields_for?
I have a table of venues where each can have many offers.
I have a form which adds offers to venues from the venues edit page.
Once I submit the form the newly created offer is shown as a partial but instead of the form clearing to allow another offer to be entered, another form is created.
So if I enter 5 offers I have 6 add new offer forms, 5 of them with the details entered into the saved ones.
My code looks like this:
venue model
class Venue < ActiveRecord::Base
has_many :offers
accepts_nested_attributes_for :offers, :reject_if => lambda { |a| a[:title].blank? }
end
edit - venue controller
class VenuesController < ApplicationController
protect_from_forgery :only => [:update, :delete, :create]
load_and_authorize_resource
def index
if
@venues = Venue.with_type(params[:venuetypes]).with_area(params[:areas]).order("average_rating DESC").all
else
@venues = Venue.all
end
@venues = @venues.paginate :per_开发者_如何学运维page => 15, :page => params[:page]
end
def new
@venue = Venue.new
end
def create
@venue = Venue.new params[:venue]
if @venue.save
flash[:notice] = 'Venue added'
redirect_to venues_path
else
render :action => :new
end
end
def edit
@venue = Venue.find(params[:id])
1.times { @venue.offers.build }
end
def update
@venue = Venue.find(params[:id])
@venue.attributes = params[:venue]
if @venue.save!
flash[:notice] = 'Venue updated successfully'
redirect_to :back
end
end
def show
@venue = Venue.find(params[:id])
@review = Review.new
end
def destroy
Venue.find(params[:id]).destroy
flash[:notice] = 'Venue deleted successfully'
redirect_to venues_path
end
end
venues edit.html.erb
<%= form_for @venue do |f| %>
<div class="edit_venue_details">
<h2 class="venue_show_orange">Offers</h2>
<% if @venue.offers.count.zero? %>
<div class="no_reviews">
No offers added yet.
</div>
<% else %>
<%= render :partial => 'offers/offer', :collection => @venue.offers %>
<% end %>
<div class="clearall"></div>
</div>
<h2 class="edit_venue_sub_header">Add a new offer</h2>
<%= f.fields_for :offers do |offer| %>
<p class="edit_venue">title: <br>
<%= offer.text_field :title, :class => "edit_venue_input" %></p>
<% end %>
<button class="submit_button" type="submit"> Save changes</button>
<% end %>
How can I prevent a new form being created on submit?
Thanks for any help its much appreciated!
edit
Try this out for your controller:
def new
@venue = Venue.new
1.times { @venue.offers.build }
end
def create
@venue = Venue.new params[:venue]
if @venue.save
flash[:notice] = 'Venue added'
redirect_to edit_venue_path
else
render :action => :new
end
end
def edit
@venue = Venue.find(params[:id])
1.times { @venue.offers.build }
end
def update
@venue = Venue.find(params[:id])
if @venue.update_attributes(params[:venue])
flash[:notice] = 'Venue updated successfully'
redirect_to edit_venue_path(@venue)
end
end
精彩评论