我希望我的网址使用破折号-
而不是下划线_
作为单词分隔符.例如,controller/my-action
而不是controller/my_action
.
我对两件事感到惊讶:
-
到_
路由.或者是吗?我将使用的最佳解决方案:as
或命名路线.
我的想法是修改Rails路由以检查该全局配置并在分派到控制器操作之前更改-
为_
.
有没有更好的办法?
我试图更好地理解 Ruby 单例和类继承。我到处都读到
def self.method_name; end`
Run Code Online (Sandbox Code Playgroud)
相当于
class << self
def method_name; end
end
Run Code Online (Sandbox Code Playgroud)
但如果那是真的,那么我希望print_constant_fails
能工作,但事实并非如此。这里发生了什么?
class SuperExample
A_CONSTANT = "super example constant"
end
class SubExample < SuperExample
def self.print_constant_works_1
puts A_CONSTANT
end
class << self
def print_constant_works_2
puts self::A_CONSTANT
end
def print_constant_fails
puts A_CONSTANT
end
end
end
Run Code Online (Sandbox Code Playgroud)
pry(main)> SubExample.print_constant_works_1
super example constant
pry(main)> SubExample.print_constant_works_2
super example constant
pry(main)> SubExample.print_constant_fails
NameError: uninitialized constant #<Class:SubExample>::A_CONSTANT
from (pry):13:in `print_constant_fails'
Run Code Online (Sandbox Code Playgroud) 我正在将应用程序升级到Rails 3.我决定使用mysql2 gem.应用程序中有一些遗留代码可以调用:
results = ActiveRecord::Base.connection.execute(sql)
Run Code Online (Sandbox Code Playgroud)
在2.3.x版本中,它使用了
results.each_hash do |row|
...
Run Code Online (Sandbox Code Playgroud)
但是使用gem mysql2,结果是类型Mysql2::Result
,它只有一个each
方法.检查文档并指定结果应该是键入字段名称的哈希值.大!
但事实上,它是一个Array
,而不是一个Hash
.
当我使用rails控制台并实例化我自己的Mysql2::Client
并在那里运行查询时,结果是一个Hash
,这就是我想要的.
在rails应用程序中,我认为最好使用ActiveRecord::Base.connection
它,因为它已经使用database.yml中的选项进行了实例化.
注意,遗憾的是结果没有映射到模型,所以我不能使用它.
我现在所做的是,例如:
result = ActiveRecord::Base.connection.execute(sql)
field_index = result.fields.index("field")
result.each do |row|
row[field_index]
end
Run Code Online (Sandbox Code Playgroud)
哪个是罪恶的丑陋.
有没有人如何让它返回哈希而不是数组?