我有一個應用程序,用戶可以在其中添加一個組織到他們的帳戶。我希望他們能夠編輯其組織,並防止其被任何其他用戶編輯。它看起來像這樣導軌正確的用戶編輯方法,未定義的方法'找到'
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'。
無法弄清楚我在這裏做錯了什麼。
這似乎是工作,但由於某種原因,我的'PARAMS [: id]'是一個字符串,我的'current_user.organization.id'是一個int。所以它工作,如果我使用current_user.organization && current_user.organization.id == params [:id] .to_f'任何想法爲什麼? – Mischa
剛剛發現如果'current_user.organization = nil'調用'.id'會產生另一個錯誤 – Mischa
@Mischa:對。你是對的。 Ruby中的比較是類型敏感的。然而,如果它是'nil',則評估永遠不會超過第一個'current_user.organization'檢查。 – Drenmi