[英]checkbox in form associated with Model in Ruby on rails
I have a Model "Startup" and I have a other Model "Categorie". 我有一个“启动”模型,而我有另一个“类别”模型。 The two tables are associated.
这两个表是关联的。
I'd like call the data of Categoria through to form of Startup, this categories displayed with a checkbox. 我想通过启动的形式调用Categoria的数据,此类别带有一个复选框。 Inside the form Startup Form I have the categorie_id.
在表单“启动表单”中,我有categorie_id。 This is the code
这是代码
<%= form_for(@startup) do |f| %>
<% if @startup.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@startup.errors.count, "error") %> prohibited this startup from being saved:</h2>
<ul>
<% @startup.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.collection_select :round_id, Round.order(:name), :id, :name, include_blank: true %>
</div>
<div class="field">
<%= f.label :category %><br />
<%= f.text_field :category_id %>
</div>
<div class="field">
<%= f.collection_select :country_id, Country.order(:name), :id, :name, include_blank: true %>
</div>
<div class="actions">
<%= f.submit %> </div> <% end %>
How to display the data of Categories within form with a checkboxs ? 如何使用复选框显示表单中类别的数据?
Any idea. 任何想法。
pdt: My english is really bad. pdt:我的英语真不好。
If a Startup can have only one Category , you can do like this in your view: 如果一家初创企业只能有一个Category ,则可以在视图中执行以下操作:
<div class="field">
<%= f.label :category %><br />
<%= f.collection_select :category_id, Category.all, :id , :name %>
</div>
This will output a dropdown menu with all the categories. 这将输出包含所有类别的下拉菜单。 Make sure that the Category model has the attribute
name
. 确保Category模型具有属性
name
。
As you said, a Startup belongs to one Category , so using radiobuttons (checkboxes are here for multiple relation, means you could choose multiple categories): 如您所说, 启动属于一个Category ,因此使用单选按钮 (此处有多个关联的复选框,意味着您可以选择多个类别):
<div class="field">
<% Category.all.each do |category| %>
<%= f.radio_button :category_id, category.id %>
<%= f.label :category_id, category.name %>
<% end %>
</div>
You may have to add <br />
tags, and html options to make it looks better. 您可能需要添加
<br />
标签和html选项,以使其看起来更好。
As MrYoshiji says, you can use: 正如Mr.Yoshiji所说,您可以使用:
It will display the category name on the screen, and the value sent will be the id. 它将在屏幕上显示类别名称,发送的值将是ID。
You can find more details here : http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select 您可以在此处找到更多详细信息: http : //api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select
I advise you to use the simple_form gem to generate your form. 我建议您使用simple_form gem生成表单。 It's a very simple gem to use and customize !
这是一个非常简单的宝石,易于使用和定制! look at it ;)
看它 ;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.