我已经研究了一些在模型中使用@属性变量(已经是attr_accessible)的Rails应用程序。我有一个艰难的时间让这个但从信息我收集name
和@name
有同样的事情在一个模型,但IM在这个可能不正确。
这些@变量如何工作,为什么有人会使用@符号变量?
要添加到当前的答案,@instance_variables
是从面向对象编程...
在
object-oriented programming
with类中,aninstance variable
是在类中定义的变量(即成员变量),该类的每个实例化对象都具有一个单独的副本或instance。
“正常”编程有变量的数据片段- strings
,integers
等等,这些都是独立和只能互动,其他的部分功能,这取决于它们的范围。
面向对象编程(OOP)可以将变量视为可编辑数据(称为classes
)。这些类可以被调用,编辑以及最重要的是交互...
#app/models/product.rb
class Product < ActiveRecord::Base
#-> class
end
def new
@product = Product.new #-> creating a new instance of the class
end
Ruby / Rails是面向对象的;它通过为您提供一系列要加载和交互的对象来起作用。最著名的例子是游戏编程:
面向对象的工作方式是调用/初始化一个类的实例(在我们的例子中Product
),允许您操纵它。
类实例将对象保存在内存中,使您可以对类本身执行操作。为此,您将类的实例存储在变量中,从而允许您与变量本身进行交互:
@product = Product.new
@product.save
-
实例变量仅在以下情况下class
有效:
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
def show
@product = Product.new #-> @product only available within ProductsController
end
end
classes
通过机架请求调用Rails中的控制器:
Request > Rack > Routes > ProductsController.new(request).show > Response
如果要@instance_variable
在类的所有方法中都可用,则必须处于instance
级别...
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
def show
@product = Product.new
product_save
end
private
def product_save
@product.save #-> @product available in instance of ProductsController class
end
end
最常见的用途@instance_variables
是存储/操作以实例为中心的数据。一个很好的示例(对于我们的Product
示例)可能是stock
级别:
#app/models/product.rb
class Product < ActiveRecord::Base
def stock
@qty / @orders
end
end
由于可以在Ruby中使用getter/setter
方法,因此可以定义类的实例值,并通过其他实例数据访问它们:
@product = Product.find x
@product.stock #-> outputs stock value for that product
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句