我有角色的用户:admin,manager,cashier。用户模型与员工模型的关系。
员工belongs_to用户和 用户has_many员工
在新表格员工中,我使用了这种方法
<%= form_for @employee, remote: true, html: {role: "form", multipart: true} do |f| %>
<div class="form-group">
<%= f.label :user_id, 'User', class: "exampleInputEmail1" %>
<%= f.select :user_id, options_for_select(@users.map {|u|[u.name, u.id]}, f.object.user_id), {prompt: "Select User"}, class: "form-control" %>
</div>
使用上面的方法,我得到了所有用户。但我想只过滤角色&#34; admin&#34;在选择。怎么做到的?
修改
employees_controller
新建并创建行动
def new
@employee = Employee.new
@users = User.all
end
def create
@employee = Employee.new(employee_params)
@users = User.all
respond_to do |format|
if @employee.save
format.html { redirect_to employees_path, notice: 'Employee was successfully created.' }
format.json { render :show, status: :created, location: @employee }
format.js
else
format.html { render :new }
format.json { render json: @employee.errors, status: :unprocessable_entity }
end
end
end
修改2
忘记添加此内容。关系用户和角色。
class User < ActiveRecord::Base
has_many :user_roles, :dependent => :destroy
has_many :roles, :through => :user_roles
end
class Role < ActiveRecord::Base
has_many :user_roles, :dependent => :destroy
has_many :users, :through => :user_roles
end
编辑3
schema.rb
create_table "roles", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "roles", ["name"], name: "index_roles_on_name", unique: true, using: :btree
create_table "user_roles", force: :cascade do |t|
t.integer "user_id"
t.integer "role_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "user_roles", ["role_id"], name: "index_user_roles_on_role_id", using: :btree
add_index "user_roles", ["user_id"], name: "index_user_roles_on_user_id", using: :btree
create_table "users", force: :cascade do |t|
t.string "name"
t.string "gender"
t.string "username"
t.string "email"
t.string "salt"
t.string "encrypted_password"
t.string "auth_token"
t.string "password_reset_token"
t.datetime "password_reset_sent_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["username"], name: "index_users_on_username", unique: true, using: :btree
add_foreign_key "user_roles", "roles"
add_foreign_key "user_roles", "users"
create_table "employees", force: :cascade do |t|
t.string "employee_code"
t.string "name"
t.string "age"
t.string "address"
t.string "telp"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end
答案 0 :(得分:0)
编辑。
您可以使用以下方式浏览管理员:
@user.roles.where(name: 'Admin')
这假设您的Role类已将角色存储在名为&#34; Name&#34;的列中。并且给管理员的名称是&#34; Admin&#34; - 如果没有,则用(your_role_column:&#39;您的管理员名称&#39;)替换括号内部。
答案 1 :(得分:0)
更好的方法是使用范围:
模特中的:
db.delete("TABLE_NAME", null, null);
控制器中的:
scope :admins, ->{ where(name: 'Admin') }