连接两个模型belongs_to/has_many 并通过下拉菜单进行选择 [英] Connecting two models belongs_to/has_many and selecting via dropdown in form
问题描述
我是 Rails 初学者,我面临一个基本问题.我找到了几个解决方案,但没有一个完全描述我的问题.我有两种模型:联系人和群组
组 has_many :contacts联系belongs_to :group
(通过设计有第三个用户模型)
在创建新联系人时,我希望用户能够通过选择选项(如下拉字段)选择该联系人所属的组.
我在他的联系人表中添加了一个 :group_id 索引:
class AddGroupIdToContacts <ActiveRecord::迁移定义改变add_column :contacts, :group_id, :integer结尾结尾
在 view/contacts/_form 中,我使用 collection_select 选项输出显示可用组的下拉字段:
<%= form_for(@contact) do |f|%><% 如果@contact.errors.any?%><div id="error_explanation"><h2><%=pluralize(@contact.errors.count, "error") %>禁止保存此联系人:</h2><ul><% @contact.errors.full_messages.each do |message|%><li><%=消息%></li><%结束%>
<%结束%>...<div class="field"><%= f.label :group_id %><br><%= f.collection_select(:group_id, Group.all, :id, :name) %>
...<div class="actions"><%= f.submit %>
<%结束%>
我可以成功输入新联系人,但在控制台中检查时我有一个空的 group_id: nil 字段.
将所选组的 id 输入到 group_id 字段的正确方法是什么,如何在 show.html.erb 中显示此条目(最好使用组 id 的名称)?
我知道这是一个基本问题,但我坚持使用 Rails 并且非常陌生.感谢您的帮助!
我尝试了上面的代码并且它工作正常.我可以保存与 group_id 的联系,而无需更改您的代码.请再次检查.您是否在控制器的参数中获取 group_id?
I am rails beginner and I am facing a basic problem. I have found a couple of solutions but none of them fully describe my problem. I have two models: Contact and Group
Group has_many :contacts
Contact belongs_to :group
(Through devise there is a third user model)
When creating a new contact I wish that the user will be able to select the group that this contact belongs to via a select option (like a dropdown field).
I have added a :group_id index to he contacts table:
class AddGroupIdToContacts < ActiveRecord::Migration
def change
add_column :contacts, :group_id, :integer
end
end
In the view/contacts/_form I have used the collection_select option to output a dropdown field showing the available groups:
<%= form_for(@contact) do |f| %>
<% if @contact.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@contact.errors.count, "error") %> prohibited this contact from being saved:</h2>
<ul>
<% @contact.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
...
<div class="field">
<%= f.label :group_id %><br>
<%= f.collection_select(:group_id, Group.all, :id, :name) %>
</div>
...
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I can input a new contact successfully but when checking in the console I have an empty group_id: nil field.
What is the correct way to input the id of the selected Group into the group_id field and how can I display this entry (preferably by using the name of the groups id) in the show.html.erb?
I know this is a basic questions but I stuck and pretty new to rails. Thanks for your help!
I tried above code and its working fine. I can save contact with group_id without any change in your code. Please check again. Are you getting group_id in params in controller?
这篇关于连接两个模型belongs_to/has_many 并通过下拉菜单进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!