Skip to content

Instantly share code, notes, and snippets.

@Preacher
Created February 5, 2012 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Preacher/1745675 to your computer and use it in GitHub Desktop.
Save Preacher/1745675 to your computer and use it in GitHub Desktop.
Auto-creating & updating child element in has_many relationship
class Channel < ActiveRecord::Base
attr_accessible :private, :title, :color_code, :subscriptions_attributes
validates_presence_of :user, :title
after_save :add_owner
belongs_to :user
has_many :subscriptions, :inverse_of => :channel, :dependent => :destroy
has_many :users, :through => :subscriptions, :uniq => true
accepts_nested_attributes_for :subscriptions, :allow_destroy => true
private
def add_owner
owner_subscription = self.subscriptions.find_or_create_by_user_id(user_id)
owner_subscription.update_attributes!(:accepted => true, :administrator => true)
end
end
class Subscription < ActiveRecord::Base
validates_presence_of :user, :channel
validates_uniqueness_of :user_id, :scope => [:channel_id], :message => 'user is already subscribed to this channel'
before_validation :set_user
belongs_to :channel, :inverse_of => :subscriptions
belongs_to :user
private
def set_user
if user_username.blank?
self.user_username = user.username
elsif user_id.blank?
self.user = User.find_by_username(user_username)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment