[英]What is the proper use of the check_box form helper?
I have two models - Client
& Topic
, with a HABTM relationship between them. 我有两个型号-
Client
和Topic
,与它们之间的关系HABTM。
I am trying to generate a series of checkboxes of the topics, on the Client form
partial. 我正在尝试在“客户端”
form
部分上生成一系列主题的复选框。
This is what I am doing: 这就是我在做什么:
<% Topic.all.each do |topic| %>
<% checked = @client.topics.include?(topic) %>
<%= f.label(:name, topic.name) %> <%= f.check_box @topics, topic.id %>
<% end %>
This is the error I get: 这是我得到的错误:
undefined method `merge' for 1:Fixnum
I know one solution is to use check_box_tag
, but that forces me to do the record updating of the associations manually. 我知道一种解决方案是使用
check_box_tag
,但这迫使我手动进行关联的记录更新。
So I would rather use the form_helper for the checkbox tag. 因此,我宁愿使用form_helper作为checkbox标签。 The docs are a bit confusing to me.
这些文档让我有些困惑。
How can I get this to work with f.check_box
. 我如何才能将此与
f.check_box
一起f.check_box
。
Thanks. 谢谢。
The code confuses me. 该代码使我感到困惑。 What
@topics
contains? @topics
包含什么? If it's a collection of of Topic
then why you are directly accessing Topic
model in the view? 如果它是
Topic
的集合,那么为什么要直接在视图中访问Topic
模型? It would be: 这将是:
@topics.each.do
rather than you 而不是你
Topic.all.each
Moreover, you are using @topics as collection inside a loop. 此外,您将@topics用作循环内的集合。 How check_box will generate checkbox from a collection?
check_box如何从集合生成复选框?
Please look at the following things: 请查看以下内容:
has_many
Topic association has_many
Topic关联之外,您还需要在Client模型中进行设置 For whatever reason, the form
helper doesn't work with check_box
. 无论出于何种原因,
form
助手都不能与check_box
一起check_box
。
So, this is the code that works: 因此,这是有效的代码:
<%= check_box_tag "client[topic_ids][]", topic.id, checked %>
According to other answers for similar questions, the helper f.check_box
is model bound and the value supplied to the checkbox is implicit from the model on the form. 根据针对类似问题的其他答案 ,辅助
f.check_box
是模型绑定的,提供给复选框的值在表单上的模型中是隐式的。 The issue is, I can't figure out how to get the implicit value of the form_helper to produce the correct tag - ie client[topic_ids][]
, so I have had to resort to check_box_tag
. 问题是,我不知道如何获取form_helper的隐式值以生成正确的标记,即
client[topic_ids][]
,因此我不得不诉诸check_box_tag
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.