[英]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. 我在搜索字段中使用jQuery的自动完成方法。 However, I don't know how to populate data from the Model in a javascript js.erb file. 但是,我不知道如何从javascript js.erb文件中的模型填充数据。
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. 我想从Course
模型访问title属性,但是它不起作用。 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: Max的编辑解决方案:我为您提供了具有标准JavaScript语法的代码,因为当您使用js.erb扩展名重命名文件时,它不再是脚本了:
$(function() {
var availableTags = <%= Course.pluck(:title) %>;
$( "#search" ).autocomplete({
source: availableTags
});
});
You can use pluck to select a single column from the database: 您可以使用pluck从数据库中选择一个列:
availableTags = <%= Course.pluck(:title).to_json %>
jQuery ->
$('#search').autocomplete
source: availableTags
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.