简体   繁体   中英

How to call a javascript variable inside Rails ERB tag

I am getting the Job search results from my Rails action by using Sunspot solr as JSON, and im creating the result view in client side by parsing the JSON data & creating HTML elements using Javascript.But from the response JSON we cant get the Job Association objects, So by using company_id field from the response JSON , am trying to access the company from the javascript itself with help of embedded ruby tag.

  function submitForm() {
   var valuesToSubmit = $('#FRM_JOB_SEARCH').serialize();
    jQuery.ajax({
    type: "POST",
    url: $('#FRM_JOB_SEARCH').attr('action'),
    data :valuesToSubmit,
    success : function(json){
      var data = JSON.parse(json);
          $.each(data, function(key, val) {
                          create_blocks(key , val);
        });
    } ,
    dataype : 'json' ,
    remote : true });

    }

  function create_blocks(key , value) {
       var feeds = eval(value)
          var company_id = feeds["company_id"];
          var company_name = '<%= Company.find_by_id('company_id').name %>';
          console.log(company_name);
   }

But this variable is not accessible inside ERB tag.How can we access a javascript variable inside RAILS erb tag.

You can't do that, because javascript is on client's side, and erb is on servers slide.

Usually if you want to pass some variable to erb , you can fetch that variable in controller in a specific action, (if you like), and pass that data to the erb.

You can take a look at railcasts here how you can do that.

As Aleks said, you can't do that because you are using ruby code in a function that is called in a callback. The simplest way to achieve what you want to do is to pass the company name in the json data you get from the server.

If you're using to_json to render the json response, try the following

 render json: @records.to_json(methods: [:company_name])

Then in the model, add the company_name method

 def company_name
   company.name
 end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM