1

所以我正在构建一个 Rails 应用程序,您可以在其中显示项目等等。我的项目控制器中有以下代码:

  def create
    @project = Project.create(params[:project].merge(:user_id => current_user.id))
    if @project.save
      redirect_to project_path(@project), :flash => {:success => 'We have created your project'}
    else
      redirect_to :back, :flash => {:error => 'Cannot allow an empty project name'}
    end
  end

这将在我拥有的模型中创建一个项目,根据我所理解的基于用户 id 并与之相关的内容:

class Project < ActiveRecord::Base
  attr_accessible :project_title, :user_id

  has_many :categories, :order => 'position', :dependent => :destroy
  has_many :tasks, :dependent => :destroy
  has_many :discussions, :dependent => :destroy
  has_many :users

  belongs_to :user

  validates :project_title, :presence => true
end

更新:用户控制器显示操作为用户显示项目

  def show
    @user = current_user

    @projects = current_user.projects.all
    @tasks = current_user.tasks.all
    @categories = current_user.categories.all
    @discussions = current_user.discussions.all
  end

*更新以显示项目控制器索引操作 *

  def index
    @project  = Project.new
    @projects = Project.all
  end

考虑到这一点,我想知道为什么我可以让用户 bob 创建一个项目,注销并且用户 jake 可以登录并查看用户 bob 项目...

我在创作上做错了吗?如果您需要,我可以显示更多代码,但我认为这将是最有用的。

4

1 回答 1

2

似乎在您的index方法中users_controller,您正在获取所有创建的项目。如果您只想显示由 current_user 创建的项目,您应该只获取这些记录。

即应该是

       @projects = current_user.projects

而你现在拥有的是(可能是)

       @projects = Projects.all

同样在你上面的 show 方法中做 current_user.projects.all没有任何意义。

current_user.projects将获取您需要的记录。

于 2012-11-21T17:04:54.113 回答