简体   繁体   中英

How to access a property of a model in rails 4 from a js.erb file?

I'm using jQuery's autocomplete method for a search field. However, I don't know how to populate data from the Model in a javascript js.erb file.

I'm using the following code:

availableTags = <%= Course.all.title %>
jQuery ->
  $('#search').autocomplete
    source: availableTags

I want to access the title property from Course model but it doesn't work. It gives a no property found error.

Thanks in advance.

EDIT SOLUTION by Max:I give you the code with standard JavaScript syntax because is no longer coffescript when you rename the file with js.erb extension:

    $(function() {
    var availableTags = <%= Course.pluck(:title) %>;
    $( "#search" ).autocomplete({
      source: availableTags
    });
  });

You can use pluck to select a single column from the database:

availableTags = <%= Course.pluck(:title).to_json %>
jQuery ->
  $('#search').autocomplete
    source: availableTags

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