Ruby on Rails button click to populate text_field

2019-07-27 05:23发布

问题:

I am trying to populate a text_field on click of a button using jQuery and have a few questions. I posted a question about this here but wasn't sure about the answer provided as it seemed overly complicated (It could be the correct but I had no luck with the implementation)...

Ruby on Rails jQuery button click populate text_field

Confirmation of doing it the way Christian mention in the other question or something simpler would be great, and sample code would be greatly appreciated. As mentioned in the other question I am very new to both ROR and jQuery.

Some more info about the question...

The button exits in both the new and edit.html.erb and is located in a form_for block next to a text_field (I have a separate button to submit the form). I want to be able to populate the field using the Ruby method SecureRandom.urlsafe_base64.

  1. Am I correct in using a button_tag?
  2. Where should the javascript file be located, I've read a bit about this and some mention creating an edit.js.erb file and have the controller also respond to javascript. I am a bit unsure about this process however and as I need similar functionality in the new and edit pages, one global jQuery function would be better.
  3. If calling a method from the controller through jQuery is right way could someone please provide some sample code of how this is done as I had no luck when trying. If it is possible to call SecureRandom.urlsafe_base64 from a js.erb file and have the field update each time the button is clicked that would be ideal.

As can be seen in the other question I got something working but am now stuck and it's becoming quite desperate.

I would be grateful for any help and sample code.

Thanks a ton!

回答1:

I'm assuming you have jQuery included and working correctly already. With that said and for simplicity, put this javascript in an app/assets/javascripts/devices.js. If you do so, ensure your application.js in the same directory includes a "//=require_tree . " (which will pull in all the files in that directory including the one you just created.) Above all, ensure you are including "application.js" in the layout that's being rendered. (likely app/views/layouts/application.html.erb)

app/assets/javascripts/devices.js:

$(function(){
  $("#deviceIDbutton").click(function(e){
      $.get("/generate_device_id", function(data){
      $("#deviceIDfield").val(data);
    });
    e.preventDefault();
  })
})

Then, add the route so the AJAX call knows what controller and action to call...

app/config/routes.rb

get '/generate_device_id', :to=>"devices#generate_device_id"

Then, add the controller action that will call the SecureRandom method you're asking for...

app/controllers/devices_controller.rb

def generate_device_id
 render :text=>SecureRandom.urlsafe_base64
end