Skip to content

Instantly share code, notes, and snippets.

@jhjguxin
Created July 2, 2012 12:19
Show Gist options
  • Save jhjguxin/3032976 to your computer and use it in GitHub Desktop.
Save jhjguxin/3032976 to your computer and use it in GitHub Desktop.
Rails Active Record Validations with relationship table(eg. foreign key)
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :cms_role
end
class User < ActiveRecord::Base
has_many :assignments, :dependent => :destroy, :uniq => true
has_many :cms_roles, :through => :assignments
has_many :cu_permits, :dependent => :destroy, :uniq => true
has_many :permits, :through => :cu_permits
attr_accessible :email, :password, :password_confirmation,
:remember_me, :username, :login, :agree,:cms_role_ids,:permit_ids
#any way it's not work fine when I want to fiter foreign key
#before_validation :update_user_permit
#def update_user_permit
# old_cms_roles = []
# (Assignment.where user_id: self.id).each do |assignment|
# old_cms_roles.append assignment.cms_role if CmsRole.exists? assignment.cms_role_id
# end
# if self.cms_roles.sort != old_cms_roles.sort
# self.permits = []
# end
#end
def update_user_permit(new_cms_role_ids = [])
new_cms_role_ids.collect!{|new_cms_role_id| new_cms_role_id.to_i if new_cms_role_id.present?}.compact!
if self.cms_role_ids.sort != new_cms_role_ids.sort
self.permits = []
end
end
end
class Auth::UsersController < ApplicationController
load_and_authorize_resource
Model_class = User.new.class
# GET /auth/users
def update
#@auth_user = Auth::User.find(params[:id])
@auth_user = User.find(params[:id])
@auth_user.update_user_permit(params[:user][:cms_role_ids]) if params[:user].key? :cms_role_ids
respond_to do |format|
if @auth_user.update_attributes(params[:user])
format.html { redirect_to auth_user_path(@auth_user), notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @auth_user.errors, status: :unprocessable_entity }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment