输入自动完成或Rails中的新功能
I have a simple doubt. I'm working on ruby on rails 5, and I have a relation where the parent is 'category' and the child is 'phrase'. My user can create phrases but I don't want a separate form to create categories, which is just an id and a name. I want in the form for phrases an input where the user can type a category and an autocomplete will pop up with the avaliable options, but if he wants a new one, he simply types it and it will create a new one when he saves the form.
我有一个简单的疑问。我正在使用rails 5上的ruby,我有一个关系,父亲是'category',孩子是'短语'。我的用户可以创建短语,但我不想要一个单独的表单来创建类别,这只是一个id和一个名字。我想在短语的形式输入一个输入,用户可以输入一个类别,自动完成将弹出可用的选项,但如果他想要一个新的,他只需键入它,它将创建一个新的,当他保存形成。
I've seen something similar with jquery-ui autocomplete but I couldn't make it work properly because it requires a predefined list inside the javascript. thank you.
我已经看到类似于jquery-ui自动完成的东西,但我无法正常工作,因为它需要在javascript内部预定义的列表。谢谢。
1 个解决方案
#1
0
a similar solution is to use datalist
and option
tags for your input. like :
类似的解决方案是为您的输入使用datalist和option标签。喜欢 :
<%= form_for @phrase do |phrase_form| %>
<%= f.text_field :name >
#=> other fields for phrase ........
<%= fields_for :category do |category_builder| %>
<%= category_builder.text_field :name, :list => "categories_list" %>
<datalist id = "categories_list" >
<% Category.all.each do |c| do %>
<option value = "<%=c.name%>" ></option>
<% end %>
</datalist>
<% end %>
<% end %>
then you add accept_nested_attributes_for :category
in phrase.rb
model file
然后在phrase.rb模型文件中添加accept_nested_attributes_for:category
once you type in text field you will get a list of available options for categories
输入文本字段后,您将获得类别的可用选项列表
other solution is to define a new methods for phrase category_name
and category_name=(name)
其他解决方案是为短语category_name和category_name =(name)定义一个新方法
def category_name=(name)
self.category = Category.find_or_create_by(:name => name)
end
then <%= f.text_field :category_name, :list => "categories_list %>"
那么<%= f.text_field:category_name,:list =>“categories_list%>”
更多相关文章
- 等待执行所有ajax回调的最佳解决方案
- 【问题解决方案】ImportError: No module named 'pygal'
- Python 黏包及黏包解决方案
- 无法安装ndg-httpsclient或者我的解决方案错误
- Linux无法连接网络解决方案
- Media-S 简介(一个开源的DRM解决方案)
- AppScan安全问题解决方案
- PLSQL乱码解决方案
- 数据库不支持中文解决方案(mysql)