仅显示属于用户的项目的问题
所以我正在构建一个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 '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可以登录并查看用户bobs项目…
我在创作上做错了吗? 如果需要,我可以显示更多代码,但我认为这将是最有用的。
似乎在users_controller
的index
方法中,您正在获取所有创建的项目。 如果要仅显示由current_user创建的项目,则只应获取这些记录。
即它应该是
@projects = current_user.projects
你现在拥有的是(可能是)
@projects = Projects.all
同样在上面的show方法中执行current_user.projects .all doens没有任何意义。
current_user.projects
将获取您需要的记录。