Last active
December 31, 2015 21:09
-
-
Save kardeiz/8045365 to your computer and use it in GitHub Desktop.
Models for http://stackoverflow.com/questions/20599679
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 Description < ActiveRecord::Base | |
belongs_to :user | |
belongs_to :product | |
belongs_to :document | |
# attr_accessible :title, :body | |
validate :check_limit | |
def check_limit | |
if self.class.where(:user_id => self.user_id).count >= 1 | |
msg = "You have reached your limit" | |
self.errors.add(:user_id, msg) | |
end | |
end | |
end | |
class Document < ActiveRecord::Base | |
belongs_to :user | |
attr_accessible :document_number, :product_ids | |
has_many :descriptions, { | |
:dependent => :destroy, | |
:before_add => [:add_user_id_to_description, :validate_description] | |
} | |
has_many :products, :through => :descriptions | |
def add_user_id_to_description(d) | |
d.user_id = self.user_id | |
end | |
def validate_description(d) | |
unless d.valid? | |
d.errors[:user_id].each do |err| | |
self.errors.add(:base, "Doc error: #{err}") | |
end | |
end | |
end | |
end | |
class Product < ActiveRecord::Base | |
belongs_to :user | |
attr_accessible :product_number, :document_ids | |
has_many :descriptions, { | |
:dependent => :destroy, | |
:before_add => [:add_user_id_to_description, :validate_description] | |
} | |
has_many :documents, :through => :descriptions | |
def add_user_id_to_description(d) | |
d.user_id = self.user_id | |
end | |
def validate_description(d) | |
unless d.valid? | |
d.errors[:user_id].each do |err| | |
self.errors.add(:base, "Doc error: #{err}") | |
end | |
end | |
end | |
end | |
class User < ActiveRecord::Base | |
attr_accessible :description, :user_name | |
has_many :products, :dependent => :destroy | |
has_many :documents, :dependent => :destroy | |
has_many :descriptions, :dependent => :destroy | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment