在 Rails 中,是否可以在模块中命名模型并仍然从 url_for
获得正确的行为? ?
例如,在这里,url_for
按预期工作:
# app/models/user.rb
class User < ActiveRecord::Base
end
# config/routes.rb
resources :users
# app/views/users/index.html.haml
= url_for(@user) # /users/1
而在放置
User
之后模型成模块,url_for
提示一个未定义的方法m_user_path
:# app/models/m/user.rb
module M
class User < ActiveRecord::Base
end
end
# config/routes.rb
resources :users
# app/views/users/index.html.haml
= url_for(@user) # undefined method 'm_users_path'
有没有可能有
url_for
忽略 M::User
中的模块并返回 user_path
对于 url_for(@user)
而不是 m_user_path
?更新
因此,在将近 5 年后,感谢 esad,这就是解决方案。这已经在 Rails 4.2 中进行了测试。
# app/models/m/user.rb
module M
class User < ActiveRecord::Base
end
end
# app/models/m.rb
module M
def self.use_relative_model_naming?
true
end
def self.table_name_prefix
'm_'
end
end
# config/routes.rb
resources :users
# app/views/users/index.html.haml
= url_for(@user) # /users/1
注意:使用
bin/rails g scaffold m/user
生成模型、 View 和 Controller 时, View 和 Controller 也将被命名空间。你需要搬家app/views/m/users
至app/views/users
和 app/controllers/m/users_controller.rb
至app/controllers/users_controller.rb
;您还需要删除对模块 M
的引用除了模型 M::User
之外的任何地方.最后,这里的目标是命名模型而不是 View 和 Controller 。使用esads解决方案,模块
M
(包含 User
)被明确告知不要出现在路由中。因此,有效地,M
被剥夺并且只有 User
遗迹。用户模型现在可以驻留在
app/views/models/m/user.rb
,用户 Controller 位于 app/views/controllers/users_controller.rb
可以在 app/views/users
中找到 View .
最佳答案
只需定义 use_relative_model_naming?
在包含模块中避免为生成的路由名称添加前缀:
module M
def self.use_relative_model_naming?
true
end
end
关于ruby-on-rails - Rails url_for 和命名空间模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4404440/