usage of remote: true in rails
When we are running our rails application URL will be changed based on the page request.
EX:
/users -------> index
/users/[id]/edit-------> edit
/users/new -------> new
Instead of changing address in the url we can make a simple ajax call by using
:remote=> true.
Working with :remote=>true:
Here i am showing remote: true with New User link of index page
Ex: <%= link_to 'New User', new_user_path, :remote => true %>
#it will make a ajax call
Equivalent html Code :
<a data-remote=true href="/users/new">New User</a>
2. Create a div tag with id in index page, in order to place your ajax response.
Ex: <div id="content"></div>
3. As an Ajax request, looking for JavaScript. In order to
serve that request, the
new
action of our controller would look like
this:
Ex:
# app/controllers/users_controller.rb
def new
@user = User.new
respond_to do |format|
format.js
end
end
in rails4---- respond_to :js
@user = User.new
respond_to do |format|
format.js
end
end
in rails4---- respond_to :js
4. Notice the format.js in the
Ex: respond_to
block; that allows the controller to
respond to your Ajax request. You then have a corresponding
app/views/users/new.js.erb
view file that generates the actual JavaScript
code that will be sent and executed on the client side.# app/views/users/new.js.erb
$('#content').html("<%= escape_javascript render 'ajaxform' %>")
5. The
app/views/users/_ajaxform.html.erb
partial contains the code for new form(i.e, _form.html.erb)(or)
We can use directly form insted of ajaxform i.e,
$('#content').html("<%= escape_javascript render 'form' %>")
***********“Practice makes the master."*************
No comments:
Post a Comment