Home > database >  NameError in Roles#new , undefined local variable or method `permissions'
NameError in Roles#new , undefined local variable or method `permissions'

Time:09-30

i'm doing role and permission. I want to add a permission checkbox to role create page, so when admin create role can tick the permission checkbox then store at role_permission.

I want the checkbox can connect with the permission_id because when i create one permission it will also show at the role create page.

Now i want to show the checkbox at the role create page but it give me some error.

role controller

def new
 @role = Role.new
 @role.company_id = params[:company_id]
 @permission = Permission.all
end

def create
 @role = Role.new(role_params)
 @company_id = Company.find(params[:role][:company_id])
 @permission_id = Permission.all
 if @role.save
   flash[:success] = "Succesful create!"
   redirect_to @role
 else
   render 'new'
 end
end

private

def role_params
  params.require(:role).permit(:name, :company_id)
end

new.html.erb

<% provide(:title, "Create Roles") %>
<h1>Create Role</h1>

<div >
  <div >
   <%= form_with(model: @role, local: true) do |f| %>
   <%= permissions.each do |permission|%>
   <%= render 'shared/error_messages', object: f.object %>

  <%= f.label :name %>
  <%= f.text_field :name, class: 'form-control' %>

  <%= f.label :permission_id %>
  <%= f.check_box_tag 'permission_ids[]', permission.id, false%>

  <%= f.hidden_field :company_id , value: 2%>

   <%= f.submit "Create Role", class: "btn btn-primary" %>
   <% end %>
 <% end %>
</div>

error show in website

error show in console

Update

error show after update

CodePudding user response:

In a controller, the variable name should be plural as its array/multiple records.

def new
 ...
 ...
 @permissions = Permission.all
end

And in a view we can use the same as below:

 <%= @permissions.each do |permission|%>
 <%= render 'shared/error_messages', object: f.object %>

Checkbox seems ok, but if you want to dig more, then can have a look at here: https://apidock.com/rails/v6.0.0/ActionView/Helpers/FormTagHelper/check_box_tag

  • Related