gpt4 book ai didi

Ruby on Rails 和使用符号调用方法基本问题

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:55 27 4
gpt4 key购买 nike

出于某种原因,我还没有完全了解 Rails 如何与 Ruby 交互/了解 Ruby 本身。

我进入正题。例如,在 Ruby on Rails 项目中,你可能有这样的东西:

class Product < ActiveRecord::Base
default_scope :order => 'title'
end

这让我很困惑。我假设我们正在调用 Product 从基 ActiveRecord 类继承的 default_scope 方法...以便我们可以设置一些选项。我们将符号 :order => 'title' 传递给它。 :order 只是 default_scope 函数中的一个散列值,并将该散列值设置为“title”吗?我理解正确吗?

另外,例如,当您开始进行基本验证时,您会得到类似这样的结果

validates :price, :numericalcity => {:greater_than_or_equal_to => 0.01 }

我知道这是做什么的,但它的语法让我大吃一惊。首先看起来符号用于静态重复使用的字符串值,但在这里我们发送一个动态符号......这是怎么回事?那么我们是符号中的符号吗?这基本上是哈希中的哈希还是它到底在做什么?我只是想在我的大脑中追踪它,以真正了解正在发生的事情。

最佳答案

您假设 default_scope 是一个继承自 ActiveRecord::Base 的方法是正确的。去here查看default_scope的源代码。

这是一种将可选哈希作为唯一参数的方法

这个,

default_scope :order => 'title'

和写一样,

default_scope( { :order => 'title' } )

在 ruby​​ 中,如果一个方法定义如下,

def foobar(options = {})
p options
end

但是注意语法上的细微差别。上面,如果您省略 () 保留 {},ruby 将其理解为完全不同的东西。 Ruby 看到一个方法 default_scope 接受一个 code block 作为它的参数。

default_scope { # code block }

这个方法定义看起来像,

def foobar(&block)
yield
end

了解 ruby​​ block 的工作原理 read this .

你可以这样调用它,

foobar :key_1 => 'value_1', "key_2" => 'value_2'

Ruby 理解它是,

foobar( { :key_1 => 'value_1', "key_2" => 'value_2' } )

哈希的键可以是也可以不是符号。

至于列属性price的验证辅助方法,

validates :price, :numericality => { :greater_than_or_equal_to => 0.01 }

是一样的,

validates( :price, { :numericality => { :greater_than_or_equal_to => 0.01 } } )

这类似于方法定义,如

def validates(column_attr, options = {})
# perform validation of column_attr
end

关于Ruby on Rails 和使用符号调用方法基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6936414/

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