[英]Rails: How do I autocomplete search for Name but save ID?
I've used this video http://railscasts.com/episodes/102-auto-complete-association-revised to set up an autocomplete search input in a form for my app. 我已经使用此视频http://railscasts.com/episodes/102-auto-complete-association-revised在我的应用程序的表单中设置自动填充搜索输入。 (The video may be for members only so I'll post my code as well. Essentially it searches a column of the DB (name) and autocompletes in a dropdown as you type. This all works fine however, what I'd like the form to do is submit the ID that correlates to the name, not the name itself.
(视频可能只适用于会员,所以我也会发布我的代码。基本上它会搜索数据库(名称)的一列,并在键入时自动填充下拉列表。这一切都正常,但是,我想要的是要执行的表单是提交与名称相关的ID,而不是名称本身。
I'm assuming theres no simple way to do this in just the view. 我假设在视图中没有简单的方法可以做到这一点。 Any help would be great.
任何帮助都会很棒。 Code below, let me know if any other code would be helpful.
下面的代码,让我知道是否有任何其他代码会有所帮助。
Thanks 谢谢
Controller: 控制器:
def game_name
game.try(:name)
end
def game_name=(name)
self.game = Game.find_by_name(name) if name.present?
end
Coffee: 咖啡:
jQuery ->
$('#play_game_name').autocomplete
source: $('#play_game_name').data('autocomplete-source')
In the view: 在视图中:
<%= f.label :game_name, "Search for a game" %>
<%= f.text_field :game_name, :class => "mlm mtm", data: {autocomplete_source: Game.order(:name).map(&:name)} %>
In addition to doing as @LukasSvoboda suggested, you can also override the select
event callback, which gets triggered when you select an item from the dropdown. 除了执行@LukasSvoboda建议之外,您还可以覆盖
select
事件回调,当您从下拉列表中选择项目时会触发该回调。 In the callback, you can set the text field (which doesn't need to be submitted) to the "label" of the selected item and set the value of a hidden field of the game id (which does need to be submitted) to the "value" of the selected item. 在回调中,您可以将文本字段(不需要提交)设置为所选项目的“标签”,并将游戏ID的隐藏字段的值(需要提交)设置为所选项目的“价值”。
In coffee: 在咖啡中:
jQuery ->
$('#play_game_name').autocomplete
source: $('#play_game_name').data('autocomplete-source')
select: (event, ui) ->
# necessary to prevent autocomplete from filling in
# with the value instead of the label
event.preventDefault()
$(this).val ui.item.label
$('#game_id').val ui.item.value
In markup: 在标记中:
<%= text_field_tag nil, nil, :id => 'play_game_name', :class => "mlm mtm", data: {autocomplete_source: Game.order(:name).map { |t| { :label => t.name, :value => t.id } } %>
<%= f.hidden_field :game_id, id: 'game_id' %> # tailor to your model
By the http://api.jqueryui.com/autocomplete/#option-source you can set data to the autocomplete. 通过http://api.jqueryui.com/autocomplete/#option-source,您可以将数据设置为自动完成。
You need to change the text_field line like: 您需要更改text_field行,如:
<%= f.text_field :game_name, :class => "mlm mtm", data: {autocomplete_source: Game.order(:name).map { |t| { :label => t.name, :value => t.id } } %>
For more advanced features consider to use select2 or chosen. 对于更高级的功能,请考虑使用select2或选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.