Display a checkbox list instead of multiple select

后端 未结 4 1356
失恋的感觉
失恋的感觉 2020-12-29 11:31

I have a model MyModel with a serialized attribute a, describing an array of symbols.

This code works :

<% form_for @my_         


        
4条回答
  •  情书的邮戳
    2020-12-29 11:56

    There is another solution worth mentioning that makes it very easy to insert records into the database if you have a has_and_belongs_to_many or has_many through relationship by using the collection_check_boxes form helper. See documentation here.

    <%= f.collection_check_boxes :mymodel_ids, MyModel::AS, :id, :name do |m| %>
      <%= m.check_box %> <%= m.label %>
    <% end %>
    

    Then, in the controller we would allow the mymodel_ids attribute:

    params.require(:mymodel).permit(:name, mymodel_ids:[])
    

    We can also set up a model validation to require that at least one of the checkboxes be checked:

    validates :mymodel_ids, presence: true
    

    An added benefit of this method is that if you later edit the mymodel record and uncheck one of the checkboxes, its record will be deleted from the many_to_many association table on save.

提交回复
热议问题