Last active
October 13, 2015 18:47
-
-
Save griffithac/4239916 to your computer and use it in GitHub Desktop.
Add Ownership to Rails 3 App
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Ownership | |
module Model | |
def self.included(base) | |
base.instance_eval do | |
before_save :set_creator_and_updater | |
belongs_to :creator, :class_name => 'User', :foreign_key => 'creator_id' | |
belongs_to :updater, :class_name => 'User', :foreign_key => 'updater_id' | |
attr_accessible :current_user | |
end | |
end | |
def current_user=(id) | |
@current_user = User.find(id) | |
end | |
def current_user() | |
@current_user | |
end | |
private | |
def set_creator_and_updater | |
if self.creator_id.nil? then | |
self.creator_id = @current_user.id | |
self.updater_id = @current_user.id | |
else | |
self.updater_id = @current_user.id | |
end | |
end | |
end | |
module Controller | |
def self.included(base) | |
base.class_eval do | |
before_filter :add_ownership_to_params | |
def add_ownership_to_params | |
model_key = self.class.to_s.gsub(/sController/, '').underscore.to_sym | |
if params[model_key].present? && current_user | |
params[model_key][:current_user] = current_user.id.to_s | |
end | |
end | |
end | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Add Modules to Your App | |
Ownership::Model | |
Ownership::Controller | |
## Include Modules in your Model and Controller | |
~~~~ruby | |
class Post < ActiveRecord::Base | |
include Ownership::Model | |
.... | |
end | |
class PostsController < ApplicationController | |
include Ownership::Controller | |
.... | |
end | |
~~~~ | |
## Add Database Columns | |
$ rails g migration add_creator_id_and_updater_id_to_posts creator_id:integer updater_id:integer | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment