Ads by ProfitSence
Close

Ruby on Rails JavaScript Examples

Last Updated on Wednesday 5th Oct 2022

javascript in rails

Rails.js provides the JavaScript half, and the regular Ruby view helpers add appropriate tags to your DOM.

form_for

  • form_for is a helper that assists with writing forms.
  • form_for takes a :remote option. It works like this:
			
					<%= form_for(@post, remote: true) do |f| %>
  ...
<% end %>

			
	

It Generates the below html

			
					<form accept-charset="UTF-8" action="/posts" class="new_post" data-remote="true" id="new_post" method="post">
  ...
</form>

			
	

form_tag

  • form_tag is very similar to form_for.
  • It has a :remote option that you can use like this.
			
					<%= form_tag('/posts', remote: true) do %>
  ...
<% end %>

			
	

It Generates the below html

			
					<form accept-charset="UTF-8" action="/posts" data-remote="true" method="post">
  ...
</form>

			
	

link_to

  • link_to is a helper that assists with generating links. It has a :remote option you can use like this.
			
					<%= link_to "a post", @post, remote: true %>

			
	

It Generates the below html

			
					<a href="/posts/1" data-remote="true">a post</a>

			
	

button_to

  • button_to is a helper that helps you create buttons.
  • It has a :remote option that you can call like this.
			
					<%= button_to "A post", @post, remote: true %>

			
	
			
					<form action="/posts/1" class="button_to" data-remote="true" method="post">
  <div><input type="submit" value="A post"></div>
</form>

			
	

Making the ajax request with remote: true helper in the View

  • It is also possible to add AJAX to the generated HTML elements using the AJAX helpers provided in Rails.
			
					<%= link_to admin_message_path(message.id), method: 'put', remote: true do %>
  <span id=<%= "button-text-#{message.id}" %>><%= display_text(message) %></span>
<% end %>

			
	
  • The Rails helper remote:true can be added to any other Rails view helper that generates a web request.
  • This will stop the default action of the object and instead perform an asynchronous request to the designated controller action as specified by the request path.