Ruby on Rails 根据另一个 table 值更新特定列

Ruby on Rails updating specific column based on another table value

我正在 Rails 测试站点上使用 Ruby,它基本上是我们实际站点的副本。更新用户数据后,我在测试和实际环境中都注意到用户 table 中同时包含 department_id 和 department_name,而不仅仅是加入 department_id 和总是从部门 table 中提取信息。当有人切换部门时,现有代码会更新用户 table 中的 department_id,但不会更新 department_name。我不确定这是如何从未实现的,因为有几个地方直接从用户 table 中提取 department_name,我手动更新了不正确的 department_name 字段。我需要在用户控制器中做什么才能让它根据部门 table 中 department_id 的内容更新用户 table 中的 department_name? (我知道我可以重新创建页面以加入 department_id 并从部门 table 中提取名称,但我真的不想重写一堆不同的页面)。

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

结束

允许在 users/_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
   ...

在您的 User 模型中:

before_save do
  self.department_name = department.name if department_id_changed?
end