Display result data without page refresh on form s

2019-05-29 08:06发布

问题:

I’m very new in ruby on rails. I’m stuck with a problem. I have a list of subjects and below this list I have a form to add subject. I’m trying to add a subject without page refresh and display this subject just below the list of subject. New added subject is inserting in database but it’s not displaying in bottom of list without page refresh. Here is my controller (subject_controller.rb)

    class SubjectController < ApplicationController
    layout 'standard'
    def list
        @subjects = Subject.find(:all)
    end
   def show
        @subject = Subject.find(params[:id])
   end
   def create
        @subject = Subject.new(params[:subject])
        if @subject.save
            render :partial => 'subject', :object => @subject
        end
   end
end  

Here is my partial file (_subject.html.erb)

<li id="subject_<%= subject.id %>">
<%= link_to subject.name, :action => 'show', :id => subject.id %>
<%= "(#{subject.books.count})" -%>
</li>

Here is my view page (list.html.erb)

<ul id="subject_list">
<% @subjects.each do |c| %>
<li><%= link_to c.name, :action => 'show', :id => c.id %>
<%= "(#{c.books.count})" -%></li>
<% end %>
</ul>
<div id="add_subject">
<%= form_for(:subject, :url => {:action => 'create'},
     :update => "subject_list", :position => :bottom,
     :html => {:id => 'subject_form'}, :remote => true) do %>
Name: <%= text_field "subject", "name" %>
<%= submit_tag 'Add', :id => 'create_button', :onClick => 'javascript:submitForm();' %>
<% end %>
</div>

Here is my js file

function submitForm(){
jQuery.ajax({
        type: 'POST',
        //url: "/subject/create",
        data:jQuery('#subject_form').serialize(),
        error: function(){  },
        success: function(data){ alert(data) },
        complete: function (){   }
        });
    return false;
 }

I'm using ruby 1.9.3 and rails 3.2.6

回答1:

you should do the following -

  1. In your list.html.erb replace

    <%= submit_tag 'Add', :id => 'create_button', :onClick => 'javascript:submitForm();' %>
    

with

<%= submit_tag 'Add', :id => 'create_button' %>

2. Create a new view create.js.erb with the following content -

$("#subject_list").innerHTML += "<%= escape_javascript(render(:partial => 'subject')) %>"

3. Update your controller method -

    if @subject.save
        #render :partial => 'subject', :object => @subject
        respond_to do |format|
            format.js
        end
    end

4. And finally in your subject partial use instance variable "@subject" instead of "subject" and discard your js file.