Rails 更正了用户编辑方法,未定义的方法'find'



我有一个应用程序,用户可以在其中将组织添加到他们的帐户中。我希望他们能够编辑他们的组织,并保护它不被任何其他用户编辑。它看起来像这样

class OrganizationsController < ApplicationController
  before_action :correct_user, only: [:edit, :update, :destroy]
  private
  def correct_user
    @organization = current_user.organization.find_by_id(params[:id])
    redirect_to root_url if @organization.nil?
  end
end

模型

class Organization < ActiveRecord::Base
  belongs_to :user
  validates :user_id, presence: true
end

class User < ActiveRecord::Base
  has_one :organization
end

通过Rspec,我可以找到current_user.organization的记录。但是,当我调用current_user.organization.find_by时,我收到一个未定义的方法"find_by"。

不知道我在这里做错了什么。

如果organization是单个记录,则不会响应find_by

此外,您正在检查organization在调用方法后是否nil。此时为时已晚。如果它是 nil ,并且您尝试在其上呼叫find_by,您将获得NoMethodError

相反,请尝试以下操作:

def correct_user
  if current_user.organization && current_user.organization.id == params[:id].to_i
    @organization = current_user.organization
  else
    redirect_to root_url
  end
end

只要组织和用户之间的关系是一对一的,你就不需要调用find@organization = current_user.organization就够了。

对不起我之前的回答。我已经修改成这个。

def correct_user
  @organization = Organization.find_by(id: params[:id])
  if current_user.id != @organization.user_id
    redirect_to root_url
  end
end

当当前用户不是组织的所有者时,将被重定向到root_url。

处理此问题的一种有效方法是在组织控制器中实现 correct_user 方法,如下所示。

 # Confirms the correct user.
  def correct_user
    @user = User.find(params[:user_id])
    redirect_to(root_url) unless current_user?(@user)
  end

调试帮助程序

控制器中添加此内容以在运行时查看哈希的内容

flash[:info] = "Hash: #{params}"

最新更新