2011-02-15 35 views
0

所以我有一個項目模型&用戶模型。每個用戶都屬於一個計劃 - 限制他們可以擁有的項目數量(即plan_id ='1'可以有1個項目,plan_id ='2'可以有3個項目等)。如何將current_user傳遞到Rails 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

如果使用current_user.projects.build,則project.user已經是current_user。任務完成。

編輯:有了HABTM,其中一個用戶是current_user。你可能會考慮第二個關聯,所以你可以說current_user.owned_projects.build,然後project.owner。

+0

ReinH,感謝您的建議。問題是我有兩個其他模型/對象,我也需要限制(存儲和客戶端)。那麼我是否也必須在用戶和這些模型之間創建關聯? – marcamillion 2011-02-15 07:33:08

相關問題