#添加代码
class ProjectTags < ActiveRecord::Base
  attr_accessible :description, :project_id, :tag_id, :user_id
####################################################################################################添加代码 
  belongs_to :project,:touch => true
  belongs_to :tag
  belongs_to :user

  validates_uniqueness_of :project_id, :scope => :tag_id
  validates_presence_of :project_id, :tag_id, :user_id
  validate :validate_user
  

  #新建project_tag的内容
  def self.add_tag(project_id, content, description=nil, user_id)
    if Tag.add_content(content)  #tag表里新建一条记录和内容字段
    @new_tag = self.new       #相应的在project_tags表里新建一条对应的记录
    @new_tag.project_id = project_id
    @new_tag.description = description
    @t_tag = Tag.where("content = ?", content).to_a   #把新添加content的那条记录的数组返回
    @new_tag.tag_id = @t_tag.first.id                  #必须用first来调用数组第一个元素
    @new_tag.user_id = user_id
    @new_tag.save
    true
    end
  end

  #根据project_id查询tag
  def self.find_tag(project_id)
    @project = Project.find(project_id)
    @project_tags = @project.project_tags
    @project_tags
  end
  
  def find_tag
    @tag = self.tags
    @tag
  end
  
  def validate_user
    errors.add :user_id, :invalid unless user.nil? || user.active?
  end

end
##################################################################################################### 添加结束
