我对params可见性问题find_agency
:
代码:
要求'sinatra / base'
module Sinatra
module AgencyRightsHelper
def self.find_agency
@agency = nil
if !params[:agency_id].nil? then
@agency = Agency.find(params[:agency_id]) and return
end
end
def before_get_agency rights_params
AgencyRightsHelper::find_agency
end
end
helpers AgencyRightsHelper
end
错误:
2017-05-10 00:01:26 - NoMethodError - undefined method `params' for Sinatra::AgencyRightsHelper:Module:
/Users/dali/perso/spacieux-be/app/helpers/agency_rights_helper.rb:18:in `before_get_agency'
/Users/dali/perso/spacieux-be/app/helpers/rights_helper.rb:61:in `before_action'
params在其他helper函数中是可见的,其中没有使用self,但我觉得有必要使用它来重用helper本身的函数。
答案 0 :(得分:0)
find_agency
是一个类方法,意味着它无法访问特定实例的属性和方法,因此您将无法访问Sinatra应用程序的给定实例的params
上课(见(Ruby,Rails) Context of SELF in modules and libraries...?)。相反,你可以创建一个这样的模块:
module AgencyRightsHelper
def find_agency
@agency = Agency.find(params[:agency_id]) if params[:agency_id].present?
end
end
然后您可以使用此方法,例如在Sinatra Application类的before
块中。