【问题标题】:problems showing only projects that belong to a user仅显示属于用户的项目的问题
【发布时间】:2013-12-05 01:29:45
【问题描述】:

所以我正在构建一个 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 项目...

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

【问题讨论】:

  • 你的表演动作是什么样的?
  • Scott S 是对的,你应该看看动作,看看你是通过一个对象而不是类调用项目...
  • 已更新以显示用户显示操作。我希望这会有所帮助
  • 可能是您正在查看的索引操作吗?请将代码发布到您的索引操作(如果存在)。

标签: ruby-on-rails ruby-on-rails-3 activerecord


【解决方案1】:

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

即应该是

       @projects = current_user.projects

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

       @projects = Projects.all

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

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

【讨论】:

  • 我更新了原帖。显示我为用户显示的显示方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-07
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多