我正在使用Ruby on Rails测试网站,它基本上是我们实际网站的副本。在更新用户数据时,我注意到在测试和实时环境中用户表中都包含department_id和department_name,而不是仅仅加入department_id并始终从department表中提取信息。当有人切换部门时,现有代码会更新users表中的department_id,但不更新department_name。如何实现这一点我不确定,因为有一些地方直接从users表中取出department_name,我手动更新了不正确的department_name字段。我需要在用户控制器中做什么才能让它根据department_id的department表中的内容更新用户表中的department_name? (我知道我可以重新创建要加入department_id的页面,而不是从dept表中提取名称,但我真的不想重写一堆不同的页面。)
users_controller.rb更新方法
def update
@user = User.find(params[:id])
email_changed = @user.email != params[:user][:email]
#need to set user's department_name so it is updated in users table
@user.update_without_password(params[:user])
successfully_updated = true
if successfully_updated
flash[:notice] = "Profile was successfully updated"
redirect_to @user
else
render "edit"
end
结束
允许在用户/ _form.html.erb
中更改部门的表单控件<% if current_user.is_admin? %>
<%= f.association :department, label: false, :collection =>
@departments, :prompt => "Select Department" %>
...
模型文件
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me,
:username, :first_name, :middle_name, :last_name, :suffix, :department_id,
:department_name
belongs_to :department
...
答案 0 :(得分:1)
在User
模型中:
before_save do
self.department_name = department.name if department_id_changed?
end