2016-05-09 4 views
3

Ich schreibe eine Web-App mit Ruby auf Schienen. In der Steuerung:Ruby/JS Wie lade ich die Seite nach dem Senden-Button neu?

def create 
@category = Category.new(category_params) 

respond_to do |format| 
    if @category.save 
    format.html { redirect_to @category, notice: 'Category was successfully created.' } 
    format.json { render :show, status: :created, location: @category } 
    format.js { render js: 'window.top.location.href = "/categories";' } 
    else 
    format.html { render :new } 
    format.json { render json: @category.errors, status: :unprocessable_entity } 
    end 

end 

Im new.html.erb:

<h1>New category</h1> 
<%= render 'form' %> 
<%= link_to 'Back', categories_path %> 

In _form.html.erb:

<%= form_for(@category) do |f| %> 
<% if @category.errors.any? %> 
<div id="error_explanation"> 
    <h2><%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:</h2> 
    <ul> 
    <% @category.errors.full_messages.each do |message| %> 
    <li><%= message %></li> 
    <% end %> 
    </ul> 
</div> 
<% end %> 
<div class="field"> 
<%= f.label :content %><br> 
<%= f.text_field :content, placeholder: "content" %> 
</div> 
<div class="field"> 
<%= f.label :description %><br> 
<%= f.text_area :description, placeholder: "description" %> 
</div> 
<div class="actions"> 
<a href="#" onclick="window.top.location.reload(true)"><%= f.submit %> 
</a> 
</div> 
<% end %> 

Ich möchte den Absenden-Button funktioniert und die neu erstellte Kategorie wird gespeichert, bevor die Seite aktualisiert wird. Im Code wird die Seite vor dem Speichern aktualisiert. Bitte helfen. Dank

+1

remove 'onclick =" window.top.location.reload (true) "' – madalinivascu

Antwort

3

Ich bevorzuge die Verwendung von unaufdringlichem Javascript. Als solche meine Antwort wie folgt:

_form.html.erb

<%= form_for(@category, remote: true) do |f| %> 
    ... 
    <div class="actions"> 
    <%= f.submit %> 
    </a> 
</div> 
<% end %> 

categories_controller.rb

def create 
    @category = Category.new(category_params) 

    respond_to do |format| 
    if @category.save 
     format.html { redirect_to @category, notice: 'Category was successfully created.' } 
     format.json { render :show, status: :created, location: @category } 
     format.js { render js: 'window.top.location.reload(true);' } 
    else 
     format.html { render :new } 
     format.json { render json: @category.errors, status: :unprocessable_entity } 
    end 
    end 
end 

Bitte beachte, dass ich format.js aktualisiert, um ein JS-Skript zu machen, dass die Seite neu geladen wird, wie du wolltest. Sie sollten jedoch wissen, dass dieses Skript auf JEDER Seite funktioniert, wenn eine JS POST-Anforderung an /categories aufgerufen wird.

3

Hallo In diesem Fall sollten Sie die Form durch js heißt

<%= form_for(@category, remote: true) do |f| %> 
<%= end%> 

Bitte lassen Sie mich wissen, einreichen, wenn es irgendein Problem.

Verwandte Themen