mardi 10 mars 2015

Ruby on Rails updating specific column based on another table value

I am working with a Ruby on Rails test site that is basically a carbon copy of our actual site. Upon updating user data, I have noticed in both test and the live environment that the user table has both department_id and department_name in it, rather than just joining on department_id and always pulling the info from the department table. The existing code updates department_id in the users table when someone switches departments, but the department_name is not updated. How this was never realized I'm not sure, because there are a few places that pull department_name from the users table directly where I've manually updated the incorrect department_name fields. What do I need to do in the users controller to get it to update the department_name in the user table based on what is in the department table for that department_id? (I know I could recreate the pages to join on the department_id and pull the name from the dept table instead, but I really don't feel like rewriting a bunch of different pages).


users_controller.rb update method



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


end


Form Control that allows department change in users/_form.html.erb



<% if current_user.is_admin? %>
<%= f.association :department, label: false, :collection =>
@departments, :prompt => "Select Department" %>
...


Model file



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
...

Aucun commentaire:

Enregistrer un commentaire