gpt4 book ai didi

ruby-on-rails - 如何从模型的类方法访问 UrlWriter url/路径生成器?

转载 作者:数据小太阳 更新时间:2023-10-29 08:41:38 25 4
gpt4 key购买 nike

我想从模型的类方法生成 url。我之前通过简单地包含 ActionController::UrlWriter 从实例方法中完成了此操作——我尝试将其包含在实例定义范围和类定义范围中,但无济于事。

class Foo < ActiveRecord::Base
# only works for instance methods
# include ActionController::UrlWriter

class << self
# results in this error: undefined method `default_url_options' for Class:Class
# include ActionController::UrlWriter
def my_method
return user_sprockets_url(:thingy => 'blue')
end
end
end

最佳答案

class ModelURL
include ActionController::UrlWriter
end

class User
@url_generator = ModelURL.new
class << self
def admin_path
@url_generator.send :admin_path
end
end
end

ruby-1.9.1-p378 ?> User.admin_path

=> "/admin"

关于ruby-on-rails - 如何从模型的类方法访问 UrlWriter url/路径生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3114515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com