problems showing only projects that belong to a user

♀尐吖头ヾ 提交于 2020-02-02 13:33:07

问题


So I am building a rails app where you can display projects and so on and so forth. I have the following code in my projects controller:

  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

this will create a project, from what I understand based on and related to the id of the user, in the model I have:

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

Updated: The User Controller Show Action to show the projects for the user

  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

*Updated to show projects controller index action *

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

With that in mind I am wondering why it is I can have a user bob create a project, log out and user jake can log in and see user bobs project...

am I doing something wrong on the create? I can show more code if you need, but I thought this would be most useful.


回答1:


It seems that in your index method of users_controller, you are fetching all the projects created. If you want to display projects created by current_user only, you should only fetch those records.

i.e. It should be

       @projects = current_user.projects

and what you have at the moment is (may be)

       @projects = Projects.all

Also in your show method above doing current_user.projects.all doensn't make any sense.

current_user.projects will fetch the records you need.



来源:https://stackoverflow.com/questions/13497912/problems-showing-only-projects-that-belong-to-a-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!