首先,我对 Rails 非常陌生。所以请忍受我的任何菜鸟错误。仍在努力寻找可靠信息的最佳来源。很多东西有点过时了。
我正在关注 Rails教程并使用密码身份验证。在我的应用程序中,我有用户和部门,它们之间的关系有 has_many。该关系称为 manager_relationship。我对用户的身份验证和授权有效。管理和取消管理按钮用于创建经理关系。我还为每个部门设置了安全密码。我希望在创建经理关系之前要求用户输入部门的密码。我在管理按钮旁边添加了一个密码字段。
楷模:
department.rb
class Department < ActiveRecord::Base
attr_accessible :department_name, :password, :password_confirmation
has_many :manager_relationships, dependent: :destroy
has_many :users, through: :manager_relationships
has_secure_password
manager_relationship.rb
class ManagerRelationship < ActiveRecord::Base
attr_accessible :department_id
belongs_to :user
belongs_to :department
validates :user_id, presence: true
validates :department_id, presence: true
end
用户.rb
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_many :manager_relationships, dependent: :destroy
has_many :departments, through: :manager_relationships
has_secure_password
查看部门/show.html.erb
...
<div class="span8">
<%= render 'manage_form' if signed_in? %>
</div>
</div>
部门网/_manage.html.erb
<%= form_for(current_user.manager_relationships.build(department_id: @department.id), remote: true) do |f| %>
<div><%= f.hidden_field :bdepartment_id %></div>
<%= f.submit "Manage Department", class: "btn btn-large btn-primary" %>
<% end %>
控制器:ManagerRelationshipsController
class ManagerRelationshipsController < ApplicationController
before_filter :signed_in_user
def create
@department = Department.find(params[:manager_relationship][:department_id])
current_user.manage!(@department)
respond_to do |format|
format.html { redirect_to @department }
format.js
end
end
上面的代码有效。它成功地创建和破坏了经理关系。但是没有认证。任何用户都可以管理任何部门。我想要求管理用户输入部门密码来创建 manager_relationship
这是我尝试过的。
部门网/_manage.html.erb
<%= form_for(current_user.manager_relationships.build(department_id: @department.id),
remote: true) do |f| %>
##################This Was Added ##############
<div>
<%= f.label :password %>
<%= f.password_field :password %>
</div>
################################################
<div><%= f.hidden_field :department_id %></div>
<%= f.submit "Manage Department", class: "btn btn-large btn-primary" %>
<% end %>
经理关系控制器
class ManagerRelationshipsController < ApplicationController
before_filter :signed_in_user
def create
@department = Department.find(params[:manager_relationship][:department_id])
########################The line below was Added ##########################
if @department.authenticate(params[:manager_relationship][:password])
###########################################################################
current_user.manage!(@department)
respond_to do |format|
format.html { redirect_to @department }
format.js
end
####################I added this##################
else
flash.now[:error] = 'Invalid password'
render 'new'
end
############################################################