How do I pass current_user into my model in Rails 3?
So I have a project model & user model. Each user belongs to a plan - that restricts the amount of projects they can have (i.e. plan_id = '1' can have 1 project, plan_id = '2' can have 3 projects, etc.).
I think I figured out how to do the actual restriction (i.e. in the project model, I do a validate :custom_method, and then define the method).
The issue is, that I need to reference the currently logged in user - i.e. current_user.
How do I do that given my code below ?
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开发者_如何学Go
#
# 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
If you're using current_user.projects.build, project.user is already current_user. Mission accomplished.
Edit: With HABTM, one of the users is current_user. You might consider a second association so you can say current_user.owned_projects.build and then project.owner.
精彩评论