I have a simple view, but Purchase belongs to :client. Therefore to access the purchases I need to provide a client_id. :
$(document).ready(function() {
var purchases = new Vue({
el: '#purchases',
data: {
purchases: []
},
ready: function() {
var that;
that = this;
$.ajax({
url: 'clients/' + CLIENT_ID + '/purchases.json', // problem
success: function(res) {
console.log(res)
that.purchases = res;
}
});
}
});
});
How do I access the client_id in the ajax request? I tried <%= @client.id %> but it get the error undefined methodid' for nil:NilClass`.
How do I pass that variable?
The answer to the question is you cant access an instance variable directly in a js function. This is because js is a client side language which only runs in your browser and ruby/rails is a server side language.
The only way you can access the variable in js is by passing it as an html data. For eg as a hidden field in your corresponding html.erb file.
<%= hidden_field_tag('client_id', @client_id) %>
and accessing it as
client_id: $('#client_id').val()
in the js file.