'Ruby on Rails checkbox got validation error
I have some issue with rails checkbox validation in the has_many. It's says checkbox need to exist even though I lardy checked the box. I include my code down below.
Role.rb (Modal)
class Role < ApplicationRecord
attr_accessor :role_permission_ids
has_many :users, dependent: :nullify
belongs_to :role_permission
validates :name, presence: true
validates :description, presence: true
# validates_acceptance_of :role_permission_ids
end
RolePermission.rb (Modal)
class RolePermission < ApplicationRecord
has_many :roles
end
new.html.erb
<% @title="Add Role" %>
<h1 class="center">Add role</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: @role, local: true, data: { turbo: false }) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name, class: 'required' %>
<%= f.text_field :name, class: 'form-control', required: true %>
<%= f.label :description, class: 'required' %>
<%= f.text_field :description, class: 'form-control', required: true %>
<%= f.label :role_permission, class: 'required' %>
<% RolePermission.all.each do |role_permission| %>
<div class="checkbox">
<%= check_box_tag "role[role_permission_ids][]", role_permission.id %>
<%= role_permission.permission %>
</div>
<% end %>
<%= f.submit "Create Role", class: "btn btn-primary" %>
<%= link_to 'Back', roles_path, class: 'btn btn-success', style: 'width: 39.7em' %>
<% end %>
</div>
</div>
So when I try to register new role it shows Role permission must exist error in the User Interface(UI)
here
Solution 1:[1]
Your role_permission is a belongs_to and what you have setup is going to pass an array which will not work. Im assuming what you actually want is a polymorphic association. check out: https://guides.rubyonrails.org/association_basics.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bryanfeller |
