I am trying to execute a Ruby method in my application_controller.rb from a button in my view. In a post yesterday, someone told me to use an Ajax call to do so because, without it, would just run on page load.
I'm very new to this and I have a hard time understanding it.
I installed the rails-Ajax gem, and it is added to my Gem file.
I followed "Integrate Ajax capabilities to Rails websites with history, bookmarking, partial refreshes, Rails flashes, user callbacks, scripts execution, redirections." untill step 5.
I just don't know what to do it next.
Here is my current configuration. The method only runs on page load:
My view:
<td><button type="button" onclick="executeit()" class="btn btn- default">executer</button></td>
<script>
function executeit() {
var selectingCommand = document.getElementById("CommandSelect");
var selectedCommand = selectingCommand.options[selectingCommand.selectedIndex].text;
var selectingServer = document.getElementById("serverlist");
var selectedServer = selectingServer.options[selectingServer.selectedIndex].text;
var username=document.getElementById("login").text;
var password=document.getElementById("password").text;
<%execute%>;
}
</script>
My method in application_controller.rb :
def execute
require 'rubygems'
require 'net/ssh'
@hostname = "smtlmon02"
@username = "test"
@password = "1234"
@cmd = "ls -al"
@cmd2 = "sudo su - -c 'ls;date'"
@cmd3 = "ls -alrt"
ssh = Net::SSH.start(@hostname, @username, :password => @password)
res = ssh.exec!(@cmd)
res2 = ssh.exec!(@cmd2)
ssh.close
puts res2
end
It would be fantastic if anyone could explain how to do it!