Reputation: 575
I am getting the Job search results from my Rails action by using Sunspot solr as JSON, and i m 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.
Upvotes: 1
Views: 1373
Reputation: 29599
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
Upvotes: 0
Reputation: 5320
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.
Upvotes: 1