Mongoid,布尔形式字段
因此,这既是一个关于如何构造布尔类型选择的问题,也是关于表单字段本身的问题。例如,如果用户在注册时必须选择一个团队(并用于演示目的),例如“向导”或“弓箭手”,那么我应该:
field :wizard, type: Boolean
field :archer, type: Boolean
但是它们只能是其中之一,那么我如何构建我的团队带有单选字段的表单,以便用户只能选择其中之一,我不确定我这样做是否正确,所以在我的表单中说我有类似的内容:
<p><%= f.label "wizard" %><%= radio_button(:user, :wizard, "True") %></p>
<p><%= f.label "archer" %><%= radio_button(:user, :archer, "True") %></p>
但这不起作用,因为您可以选择想要多少物品就多少。如何防止用户选择多个单选选项?
So this is sort of both a question about how to structure boolean sort of selections and the form fields themselves. For example If the user when signing up has to choose a team (and for demonstration purposes) like "wizard" or "archer", so like should I have:
field :wizard, type: Boolean
field :archer, type: Boolean
However they can only be one or the other, so how do I structure my forms with radio fields so that users can only select one or the other, I'm not sure if I'm doing this right so in my form say i'd have something like:
<p><%= f.label "wizard" %><%= radio_button(:user, :wizard, "True") %></p>
<p><%= f.label "archer" %><%= radio_button(:user, :archer, "True") %></p>
But so this doesn't work because you can select as many items as you want. How do I prevent the user from selecting more than one radio selection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
单选按钮不太适用于 HTML 中的不同字段。为了使它们相关以便您只能选择一个,它们的 name 属性值必须相同。您的生成名称值为“user.wizard”和“user.archer”。您将需要类似的内容:
然后在模型中添加代码,该代码可以取消选定的角色以适当地设置布尔字段。
总的来说,我建议更改您的数据模型,将角色作为字符串字段,或者规范化并使 role_id 成为一个真实字段,指向包含角色的单独表(用户 own_to :role,角色 has_many :users)。这样,如果添加新角色,则无需更改任何代码,只需向表中添加一行即可。您仍然可以在用户模型上使用布尔方法(例如,user.is_wizard?),但它们将根据角色进行计算。
Radio buttons don't quite work across different fields in HTML. In order for them to be related such that you can only pick one, they must have the same value for the name attribute. Yours are being generated with name values of "user.wizard" and "user.archer". You would need something like:
and then have code in the model that plucks off the selected role to set your boolean fields appropriately.
Overall though, I would recommend changing your data model to have role as a string field, or normalize and make role_id a real field, pointing to a separate table which contained the roles (user belongs_to :role, role has_many :users). In that way, if you add a new role, you won't need to change any code, just add a row to the table. You can still have the boolean methods on the User model (e.g., user.is_wizard?), but they would be calculated based on the role.