Mysql RubyonRails基于另一个表值更新特定列
我正在使用一个RubyonRails测试站点,它基本上是我们实际站点的副本。在更新用户数据时,我注意到在测试和实时环境中,用户表中同时包含department_id和department_name,而不仅仅是加入department_id并总是从department表中提取信息。当有人切换部门时,现有代码会更新用户表中的部门id,但不会更新部门名称。我不确定这是怎么实现的,因为有几个地方直接从用户表中提取部门名称,我手动更新了不正确的部门名称字段。我需要在用户控制器中执行什么操作才能使其根据部门表中该部门id的内容更新用户表中的部门名称?(我知道我可以在department_id上重新创建要加入的页面,并从dept表中提取名称,但我真的不想重写一堆不同的页面) 用户\u controller.rb更新方法Mysql RubyonRails基于另一个表值更新特定列,mysql,ruby-on-rails,ruby-on-rails-3,Mysql,Ruby On Rails,Ruby On Rails 3,我正在使用一个RubyonRails测试站点,它基本上是我们实际站点的副本。在更新用户数据时,我注意到在测试和实时环境中,用户表中同时包含department_id和department_name,而不仅仅是加入department_id并总是从department表中提取信息。当有人切换部门时,现有代码会更新用户表中的部门id,但不会更新部门名称。我不确定这是怎么实现的,因为有几个地方直接从用户表中提取部门名称,我手动更新了不正确的部门名称字段。我需要在用户控制器中执行什么操作才能使其根据部门
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
结束
允许在用户中更改部门的表单控件/\u 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
...
class用户
在您的用户
型号中:
before_save do
self.department_name = department.name if department_id_changed?
end
正是我需要的。谢谢