开发者

Mongoid, boolean form fields

开发者 https://www.devze.com 2023-03-06 11:47 出处:网络
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

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",开发者_JS百科 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?


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:

<p><%= f.label "wizard" %><%= radio_button(:user, :role, "wizard") %></p>
<p><%= f.label "archer" %><%= radio_button(:user, :role, "archer") %></p>

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消