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