Heim > Datenbank > MySQL-Tutorial > 模型层的写作风格以及through

模型层的写作风格以及through

WBOY
Freigeben: 2016-06-07 15:04:19
Original
1361 Leute haben es durchsucht

# -*- coding: utf-8 -*- class User ActiveRecord::Base ----------------------------- include Activity::UserMethods end --------------------------------------------------------------------------------------------------------- class Activity


# -*- coding: utf-8 -*-
class User

  -----------------------------

  include Activity::UserMethods
end

---------------------------------------------------------------------------------------------------------

class Activity   attr_accessible :title, :content, :start_time, :end_time

  belongs_to :creator, :class_name => 'User', :foreign_key => :creator_id

  validates  :creator, :presence => true
  validates  :title,   :presence => true
  validates  :content, :presence => true

  validates :start_time, :end_time, :presence => true

  validate :validate_start_and_end_time

  def validate_start_and_end_time
    errors.add(:base,'开始时间必须早于结束时间') if self.start_time > self.end_time
  end

  module UserMethods
    def self.included(base)
      base.has_many :activities, :foreign_key => :creator_id
    end
  end


  include ActivityMembership::ActivityMethods

end

---------------------------------------------------------------------------------------------------------

class ActivityMembership   attr_accessible :activity, :user

  belongs_to :user
  belongs_to :activity, :foreign_key => :activity_id

  validates  :user,     :presence => true
  validates  :activity, :presence => true



  module ActivityMethods
    def self.included(base)
      base.send :include, InstanceMethods
      base.has_many :activity_memberships
      base.has_many :members, :through => :activity_memberships, :source => :user
    end

    module InstanceMethods
      def add_member(user)
        self.activity_memberships.create :user => user
      end

      def remove_member(user)
        self.activity_memberships.where(:user_id=>user.id).destroy_all
      end
    end
  end
end

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage