ruby on rails - How can I stop a form repeating using fields_for? -
i have table of venues each can have many offers.
i have form adds offers venues venues edit page.
once submit form newly created offer shown partial instead of form clearing allow offer entered, form created.
so if enter 5 offers have 6 add new offer forms, 5 of them details entered saved ones.
my code looks 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 |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 new offer</h2> <%= f.fields_for :offers |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 prevent new form being created on submit?
thanks appreciated!
edit
try out 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
Comments
Post a Comment