Ruby on rails Rails中断表中的嵌套模块\u name\u前缀
我试图在Rails应用程序中一致地使用嵌套的模块/类定义,而不是紧凑的(Ruby on rails Rails中断表中的嵌套模块\u name\u前缀,ruby-on-rails,ruby,namespaces,Ruby On Rails,Ruby,Namespaces,我试图在Rails应用程序中一致地使用嵌套的模块/类定义,而不是紧凑的(:)语法。但是,它并不总是加载模块文件本身,其中包含表\u名称\u前缀 在Ruby 2.1.1上使用Rails 4.1.8 rails new my_app ... rails g scaffold User rails g scaffold Blog::Post 这将创建app/models/blog.rb: module Blog def self.table_name_prefix 'blog_' e
:
)语法。但是,它并不总是加载模块文件本身,其中包含表\u名称\u前缀
在Ruby 2.1.1上使用Rails 4.1.8
rails new my_app
...
rails g scaffold User
rails g scaffold Blog::Post
这将创建app/models/blog.rb
:
module Blog
def self.table_name_prefix
'blog_'
end
end
似乎有很多方法可以防止Rails自动加载blog.rb
。最简单的例子是通过helpers
将app/helpers/blog/posts\u helper.rb更改为:
module Blog::PostsHelper
end
致:
启动服务器,访问/users
,然后访问/blog/posts
:
SQLite3::SQLException: no such table: posts: SELECT "posts".* FROM "posts"
类似的问题可能发生在其他地方,例如模型试验中。这不仅限于帮手
解决这个问题的最好办法是什么?显式加载
blog.rb
和任何其他名称空间模块?一个不依赖自动加载的解决方案是将模型设置为从以下内容继承,而不是直接从ActiveRecord::Base
继承:
class CustomActiveRecordBase < ActiveRecord::Base
self.abstract_class = true
# If no table name prefix has been defined, include the namespace/module as
# table name prefix, e.g., Blog:: -> blog_
def self.table_name
# If a table_name_prefix has been defined, follow default behaviour
return super if full_table_name_prefix.present?
# Find the prefix, e.g., Blog::Post -> 'blog', User -> ''
prefix = model_name.name.deconstantize.underscore
# If no prefix, follow default behaviour
return super unless prefix.present?
# Otherwise add the prefix with an underscore
"#{prefix}_#{super}"
end
end
class CustomActiveRecordBaseBlog_
def self.table_名称
#如果定义了表名称前缀,请遵循默认行为
如果存在完整的\u表\u名称\u前缀,是否返回super?
#查找前缀,例如Blog::Post->“Blog”,User->”
prefix=model_name.name.deconstantize.下划线
#如果没有前缀,则遵循默认行为
返回super,除非前缀为.present?
#否则,请使用下划线添加前缀
“{prefix}{super}”
结束
结束
这样就不需要在blog.rb
中定义self.table\u name\u prefix
可以通过lib/templates/active_record/model/model.rb
和module.rb
中的相应文件,将这些设置为未来模型的默认值
这一切都可以通过monkey补丁
ActiveRecord::Base
来完成,但这会干扰其他类,例如ActiveRecord::SchemaMigration
,它没有表前缀。我能够重现这个问题-谢谢Anthony。我会在github上创建一个问题,看看团队怎么说。也许。。。虽然我更多的是寻找确保blog.rb
加载的最佳方法,而不是建议对Rails进行更改。这显然不是很多人遇到的问题。。。
class CustomActiveRecordBase < ActiveRecord::Base
self.abstract_class = true
# If no table name prefix has been defined, include the namespace/module as
# table name prefix, e.g., Blog:: -> blog_
def self.table_name
# If a table_name_prefix has been defined, follow default behaviour
return super if full_table_name_prefix.present?
# Find the prefix, e.g., Blog::Post -> 'blog', User -> ''
prefix = model_name.name.deconstantize.underscore
# If no prefix, follow default behaviour
return super unless prefix.present?
# Otherwise add the prefix with an underscore
"#{prefix}_#{super}"
end
end