使用ruby 2.6和rails 5.2 并且还使用rolify宝石。
我在用户编辑视图中传递了一个嵌套属性,以使角色可以选择(可编辑)。但是,我得到了
undefined method `name' for nil:NilClass
In my edit view.
我正在用户编辑视图中使用此代码段
<%= form_for(@user, url: account_user_path(@user), html: {class: 'form-horizontal'}) do |f| %>
<%= select_tag "user[role]", options_for_select(@choices, @user.account.roles.first.name), class:'form-control'%>
end
我在控制器中。
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update,:destroy]
........
def edit
set_choices
end
def set_choices
@choices = []
@choices << ["Admin", 'admin']
@choices << ["User", 'user']
end
......
private
def user_params
params.require(:user).permit(:name, :email, :role)
end
class RolifyCreateRoles < ActiveRecord::Migration
def change
create_table(:roles) do |t|
t.string :name
t.references :resource, :polymorphic => true
t.timestamps
end
create_table(:users_roles, :id => false) do |t|
t.references :user
t.references :role
end
add_index(:roles, :name)
add_index(:roles, [ :name, :resource_type, :resource_id ])
add_index(:users_roles, [ :user_id, :role_id ])
end
end
答案 0 :(得分:0)
如果用户没有角色,则可以使用安全导航,它将使用以下代码处理情况
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let company of filterOption | async" [value]="company.name"> {{ company.name }} </mat-option>
</mat-autocomplete>