I have a CRUD application set up in Ruby on Rails 3 – its working as is. I need to add some ajax here. My first requirement is to retrieve a customised form when clicking on a New Form link. This is the link I have at this point:
<%= link_to 'New Book', new_book_path(:subject_id=>@subject.id), :remote=>true %>
For my controller I’ve made the following adjustment to the new book action:
def new
@book = Book.new
if params[:subject_id].to_i >0 then
@book.subject_id = params[:subject_id]
end
if request.xhr?
respond_to do |format|
format.html # new.html.erb
format.json { render json: @book }
render :layout => false, :file=>'app/views/books/_form'
return false
end
else
respond_to do |format|
format.html # new.html.erb
format.json { render json: @book }
end
end
end
I checked in firebug and clicking on the link generated returns the form html however I have no idea how to handle the response? Please do help.
Instead of responding with HTML respond with .js
Inside your .js.erb file could be something like this
That way it renders and returns the form HTML but also gives the js code to append the HTML.