ruby-on-rails - Rails url_for 和命名空间模型

标签 ruby-on-rails ruby-on-rails-3 namespaces url-for

在 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/usersapp/views/usersapp/controllers/m/users_controller.rbapp/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/

相关文章:

ruby-on-rails - rails : 'Could not find table' in a many-to-many relationship

ruby-on-rails - Rails 引擎存在外键问题

ruby-on-rails - 接受嵌套属性和过滤器

ruby-on-rails - 判断字符串是否只包含数字

mysql - Rails 3 App Mysql2::Error - 新手无法写入数据库

ruby-on-rails - 'gem 安装' 和 'sudo gem install'

javascript - 如何将 javascript 添加到 Rails 5 中的单个 View ?

.net - 当公司拥有所有大写字母时命名空间的命名指南

c++ - 使用可选的 'struct' 关键字时出现 g++ 警告

c# - 实际定义时为 "Namespace prefix not defined"