模型层的写作风格以及through

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

<link href="/js/syntaxhighlighter/SyntaxHighlighter.css" rel="stylesheet" type="text/css" />


# -*- coding: utf-8 -*-
class User < ActiveRecord::Base

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

include Activity::UserMethods
end

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

class Activity < ActiveRecord::Base

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 < ActiveRecord::Base
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

郑重声明:本文版权包含图片归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们(delete@yzlfxy.com)修改或删除,多谢。

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

留言与评论(共有 0 条评论)
昵称:
匿名发表
   
验证码: