gpt4 book ai didi

html - 我需要在 html.erb ruby​​ 中创建一个动态选择

转载 作者:数据小太阳 更新时间:2023-10-29 08:59:42 26 4
gpt4 key购买 nike

早上好。我是 Ruby 的新手,遇到了一个小问题。

在表单中,我想选择类别。类别可以由用户插入,因此选择必须是动态的。

我试过这样的:

<div class="input-field">
<select class="multiple">
<%= f.select :category, Category.all.collect {|x| [x.name, x.id]} %>
</select>
</div>

它有效,但在 chrome 控制台上,看起来像这样:

<div class="input-field">
<select class="multiple"></select>
<option value="2">Pastasciutta</option>
<option value="3">Vegetariano</option>
</div>

类别 ID 已正确用作值,并且列表已正确显示。但是,如您所见,“选项”在“选择”标签之外。你能解释一下为什么吗?我该如何解决这个问题?该列表仅显示为列表,但我想标记和取消标记 x 个类别。

我的 Ruby 版本 -> 2.3.1

----编辑----

     _form.html.erb
<%= form_for(recipe) do |f| %>
<% if recipe.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2>

<ul>
<% recipe.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>

<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>

<div class="field">
<%= f.label :time %>
<%= f.number_field :time %>
</div>

<div class="field">
<%= f.label :price %>
<%= f.text_field :price %>
</div>

<div class="field">
<%= f.label :recipe %>
<%= f.text_area :recipe %>
</div>


<div class="input-field">
<%= f.select :category, Category.all.collect {|x| [x.name, x.id]}, {}, class: "multiple" %>
</div>

<br>

<div class="actions">
<%= f.submit %>
</div>
<% end %>

这就是渲染的内容:

http://prnt.sc/cfqmp6

最佳答案

行:

<%= f.select :category, Category.all.collect {|x| [x.name, x.id]} %>

已经在渲染 <select>标记元素的一部分,您通过将上面的行放在另一个 <select> 中来复制此元素.改变这个:

<select class="multiple">
<%= f.select :category, Category.all.collect {|x| [x.name, x.id]} %>
</select>

对此:

<%= f.select :category, Category.all.collect {|x| [x.name, x.id]}, {}, class: "multiple" %>

最后两个参数是 optionshtml_options到选择标签。请参阅:http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-select

关于html - 我需要在 html.erb ruby​​ 中创建一个动态选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39396913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com