Created
February 5, 2012 13:50
-
-
Save Preacher/1745675 to your computer and use it in GitHub Desktop.
Auto-creating & updating child element in has_many relationship
This file contains 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
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 |
This file contains 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
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