[英]Rails string array and PostgreSQL
I have a Rails model named Container
with a column named products
. 我有一个名为
Container
的Rails模型,其中有一个名为products
的列。 It is a string array as supported by Postgres and the 'postgres_ext' gem. 这是Postgres和'postgres_ext'gem支持的字符串数组。
The relevant portion of the GEMFILE is: GEMFILE的相关部分是:
gem 'rails', '3.2.9'
gem 'pg'
gem 'postgres_ext'
gem 'activerecord-postgres-hstore', git: 'git://github.com/engageis/activerecord-postgres-hstore.git'
The relevant portion of the migration is: 迁移的相关部分是:
t.string :products, array: true
I am writing a public method in my Container
model which adds products to this array. 我正在我的
Container
模型中编写一个公共方法,该方法将产品添加到此数组中。 The method looks like this: 该方法如下所示:
attr_accessible :products
def add_to_products(product)
if products.blank? || products.size == 0 ## product array is either uninstantiated or blank
products = [product.id]
else
unless products.include? product.id
products << product.id
end
end
end
These are the results in irb/console: 这些是irb / console中的结果:
pry(main)> c = Container.first
=> #<Container id: "2765cc19-98f8-4e42-a1be-538788424ec7", name:....
pry(main)> p = Product.first
=> #<Product id: "319a25ae-87fe-4769-a9de-1a8e0db9e84f", name: ....
pry(main)> c.add_to_products(product)
pry(main)> c.products
=> nil
pry(main)> c.products= [] << "319a25ae-87fe-4769-a9de-1a8e0db9e84f"
pry(main)> c.products
=> ["319a25ae-87fe-4769-a9de-1a8e0db9e84f"]
I am scratching my head to figure out what's wrong in the add_to_products
method. 我正在
add_to_products
以找出add_to_products
方法中的问题。 Can someone throw some light on this weird situation? 有人可以揭露这种奇怪的情况吗? Why is the value not being set when I pass it through this method?
通过此方法传递值时,为什么未设置该值?
This issue is actually arising out of the use of <<
. 实际上,此问题是由于使用
<<
。 Rails does not track in place modifications of attributes ( see this issue ). Rails不会就位跟踪属性的修改( 请参见此问题 )。 I outline in the usage notes that you want to avoid the
<<
operator when using arrays, as rails will not see this change, it will actually cause issues with default values. 我在使用说明中概述了在使用数组时要避免使用
<<
操作符,因为rails不会看到此更改,实际上会导致默认值出现问题。
This can also be seen by checking the products_changed?
这也可以通过查看
products_changed?
看到products_changed?
state. 州。 It will be false when you use
<<
. 当您使用
<<
时,它将是错误的。
This has got to do with the fact that in Ruby assignments create local variables unless you explicitly state the receiver, which is self
in this case. 这与以下事实有关:在Ruby分配中,除非您明确声明接收方(在这种情况下为
self
,否则它会创建局部变量。 So: 所以:
products = [product.id]
...will create a local variable named products
. ...将创建一个名为
products
的局部变量。 Whereas: 鉴于:
self.products = [product.id]
...is what you are really looking for. ...是您真正想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.