简体   繁体   English

带有Postgres数组的Ruby on Rails

[英]Ruby on Rails with Postgres Arrays

I'm currently having an issue with Ruby on Rails (4.2.5) and Postgres (9.4.5) Arrays. 我目前在Ruby on Rails(4.2.5)和Postgres(9.4.5)数组上遇到问题。 The model attribute believes it is a type String which isn't working when trying to assign an Array. model属性认为它是String类型,在尝试分配Array时不起作用。 My migration has: 我的迁移有:

# create a urls array
t.text :urls, array: true, default: []

Then in my controller I have: 然后在我的控制器中:

def create
  @lead = Lead.new(lead_params)
  ...
end

def lead_params
  params.require(:lead).permit(:name, :base_url, urls: [])
end

Unfortunately, when debugging with byebug I see: 不幸的是,当使用byebug进行调试时,我看到:

(byebug)  lead_params['urls'].class
Array
(byebug) @lead.urls.class
String
(byebug) @lead.urls      
"[\"asd\", \"\", \"\", \"\", \"\"]"

The :urls attribute of my Lead class isn't thinking it is an Array. Lead类的:urls属性不认为它是一个数组。 I have no code in my model (which might be the problem?). 我的模型中没有代码(可能是问题所在?)。

Any thoughts much appreciated! 任何想法表示赞赏!

您可能想要将类型从text更改为string

t.string :urls, array: true, default: []

Thanks to the comment from @muistooshort I found the database schema was indeed wrong. 感谢@muistooshort的评论,我发现数据库架构确实是错误的。 Somehow in all of my Docker wisdom I had managed to get schema.rb out of sync with the actual migrations. 以我所有的Docker智慧,我设法使schema.rb与实际迁移不同步。

Now the schema.rb correctly shows: 现在schema.rb正确显示:

t.text     "urls",            default: [],              array: true

And everything works as expected :-) 一切都按预期工作:-)

The trick was the run the following: 诀窍是运行以下命令:

rake db:drop
rake db:create
rake db:migrate

I think I had previously run some rake db:rest commands which seem to have led to the issue. 我想我以前曾经运行过一些rake db:rest命令,这似乎导致了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM