[英]HABTM association dropdown select
I am trying to create a dropdown select on a form. 我正在尝试在表单上创建一个下拉选择。 I have a HABTM association between professors and classrooms: 我在教授和教室之间建立了HABTM协会:
Classroom Model: 课堂模式:
class Classroom < ApplicationRecord
has_and_belongs_to_many :professors
end
Professor Model: 教授模式:
class Professor < ApplicationRecord
has_and_belongs_to_many :classrooms
end
Strong Params: 强参数:
def classroom_params
params.require(:classroom).permit(:name, :professor_ids => [])
end
I am trying to find a way to use f.select
instead of select_tag
inside the form. 我正在尝试找到一种使用f.select
而不是select_tag
的形式。 But when I do it, the database does not save the values. 但是,当我这样做时,数据库不会保存值。 This way works: 这种方式有效:
<%= form_for @classroom do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
<% array = Professor.all.map { |professor| [professor.user.name, professor.id] } %>
<%= select_tag "classroom[professor_ids][]", options_for_select(array) %>
<% end %>
But I am trying like that and it is not working: 但是我正在尝试那样,它不起作用:
<%= form_for @classroom do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
<% array = Professor.all.map { |professor| [professor.user.name, professor.id] } %>
<%= f.select :professor_ids, options_for_select(array) %>
<% end %>
The view works correctly but when I submit the form, the value doesn't go to to the classroom_params. 该视图可以正常工作,但是当我提交表单时,该值不会传递到classical_params。 I tried to debug it stopping the controller after the submit and I got this: 我尝试调试它,在提交后停止控制器,我得到了:
The params came correctly with all the information submitted, but the classroom_params came missing the professor_ids. 这些参数正确提交了所有提交的信息,但是教室参数缺少了Professor_id。 Is there a way to do this dropdown using f.select
? 有没有办法使用f.select
进行此下拉菜单?
You whitelisted the array of 'professor_ids', but your 'select' input returns 1 string ( "prefessor_ids" => "2"
from you screenshot). 您将“ professor_ids”数组列入白名单,但是“ select”输入返回1个字符串(屏幕快照中的"prefessor_ids" => "2"
)。 Maybe you want to set the select as 'multiple'? 也许您想将选择设置为“多个”? (I have not tested it, but i think params will be whitelisted correctly after that) (我尚未测试过,但我认为之后参数会正确列入白名单)
<%= form_for @classroom do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name %><br>
<%= s.collection_select :professor_ids, Professor.all, :id, :name, multiple: true %>
<% end %>
where 哪里
class Professor
...
delegate :name, to: :user
end
Update 更新
You probably don't have 'cfg' variable in your controller action. 您的控制器操作中可能没有“ cfg”变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.