Created
October 8, 2012 16:32
-
-
Save samiron/3853453 to your computer and use it in GitHub Desktop.
Rails 3: Ajax Link
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#FILE: app/controllers/cities_controller.rb | |
class CitiesController < ApplicationController | |
#When you do a ajax request the respond handler is ':js' | |
#So format.js will work. To render a response the new.js.erb | |
#file will be used. | |
def new | |
@city = City.new | |
respond_to do |format| | |
format.js # It will look for new.js.erb | |
format.html # It will look for new.html.erb | |
end | |
end | |
#Even if you dont write the "respond_to" block | |
#it will use proper render file based on request handler. | |
#Calling edit via ajax => edit.js.erb | |
#Calling edit via html => edit.html.erb | |
def edit | |
@city = City.find(params[:id]) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- FILE: views/cities/index.html.erb --> | |
<!-- | |
In index page we will show "Create" and "Edit" link. | |
Clicking on those links will show the form within the same page. | |
Basically, we will have a content placeholder with id="main_content" | |
where the form will be shown | |
--> | |
<div id="city_list"> | |
<!-- Show the index page content here --> | |
</div> | |
<%= link_to 'Create', new_city_path, :remote => true %> | | |
<%= link_to 'Edit', edit_city_path(city), :remote => true %> | |
<div id="main_content"> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
FILE: views/cities/new.js.erb | |
FILE: views/cities/edit.js.erb | |
Both has same content | |
*/ | |
/* | |
The form is rendered and stored in "comment_form" variable. | |
Then the whole form is inserted into the DIV with id=main_content | |
*/ | |
var comment_form = $('<%= j(render(:partial => "form"))%>'); | |
$('#main_content').html(comment_form); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment