如何在Rails 3中将current_user传递给我的模型?

时间:2011-02-15 05:23:27

标签: validation ruby-on-rails-3

所以我有一个项目模型&用户模型。每个用户都属于一个计划 - 限制他们可以拥有的项目数量(即plan_id ='1'可以有1个项目,plan_id ='2'可以有3个项目,等等)。

我想我想出了如何进行实际限制(即在项目模型中,我进行验证:custom_method,然后定义方法)。

问题是,我需要引用当前登录的用户 - 即current_user。

如果我的代码如下,我该怎么做?

Projects Controller


  def create
    @project = current_user.projects.build(params[:project])
    if @project.save
      respond_with(@project, :status => :created, :location => @project) do |format|
        flash.now[:notice] = 'Project was successfully created.'
        format.html { redirect_to(@project) }
        format.js   { render :partial => "projects/show", :locals => {:project => @project}, :layout => false, :status => :created }
      end
    else
      respond_with(@project.errors, :status => :unprocessable_entity) do |format|
          format.js   { render :json => @project.errors, :layout => false, :status => :unprocessable_entity }
          format.html { render :action => "new" }
      end
    end
  end
end

Project.rb


# == Schema Information
# Schema version: 20110131093541
#
# Table name: projects
#
#  id          :integer         not null, primary key
#  name        :string(255)
#  description :string(255)
#  notified    :boolean
#  created_at  :datetime
#  updated_at  :datetime
#  client_id   :integer
#

class Project < ActiveRecord::Base

  has_and_belongs_to_many :users

  belongs_to :client
  has_many :stages, :dependent => :destroy, :order => 'created_at DESC'
  has_many :comments

  validate :number_of_projects

    def number_of_projects
      current_user.projects.count <= current_user.plan.num_of_projects
    end

end


User.rb


# == Schema Information
# Schema version: 20110214082231
#
# Table name: users
#
#  id                   :integer         not null, primary key
#   {edited for brevity}
#  plan_id              :integer
#

class User < ActiveRecord::Base


  before_create :assign_to_trial_plan

  has_and_belongs_to_many :projects
  #{edited for brevity} 
  belongs_to :plan


  def role_symbols
    roles.map do |role|
      role.name.underscore.to_sym
    end
  end

  def space
    total_size = 0
      if self.uploads.count > 0
        self.uploads.each do |upload|
          total_size += upload[:image_file_size]
        end
      end
    total_size  
  end

  def assign_to_trial_plan
    self.plan_id = '5'  #make sure to update this if the Trial plan ID ever changes    
  end 

end

1 个答案:

答案 0 :(得分:1)

如果您使用的是current_user.projects.build,则project.user已经是current_user。完成任务。

编辑:使用HABTM,其中一个用户是current_user。你可以考虑第二个关联,这样你就可以说current_user.owned_projects.build然后是project.owner。