Ruby on Rails 未定义方法 'each' for #<String:0x7efa908> 错误



我试图在html中浏览一个字符串数组,但得到"#的未定义方法'each'"错误。 错误图像

这是行星类的类定义

class CreatePlanets < ActiveRecord::Migration[5.0]
def change
create_table :planets do |t|
t.string :name, null: false
t.string :image, null: false
t.string :description, array: true, default: '{}'
t.timestamps
end
end
end

这是 html 页面

<!DOCTYPE html>
<html>
<head>
<title><%= @planet.name %></title>
</head>
<body>
<h1><%= @planet.name %></h1>
<%= image_tag @planet.image %>
<ul>
<% @planet.description.each do |x| %>
<li><%= x %></li>
<% end %>
</ul>
</body>
</html>

这是我迁移它的方式

p1 = Planet.create(name: "Sun", image: "/../assets/images/sun.jpg", description: ["The center of the solar system and the only star in solar system.", 
"Due to its huge mass, other planets in solar system form radiant power between sun and itself, maintaining the rotation around sun", 
"The surface temperature is said to be about 6000 degree celcius."])

起初,我在类定义中尝试了 default: [],但它失败了,所以我将其更改为"{}"。如果有人知道如何以任何一种方式处理这个问题,请告诉我。

谢谢。


编辑:

在我尝试@planet.description.lines.each之后,输出会变为此。电流输出

它在同一行上具有列表,并且还包括 [],它应该是数组的外部容器


更新:

现在我把 CreatePlanets 类改成了

class CreatePlanets < ActiveRecord::Migration[5.0]
def change
create_table :planets do |t|
t.string :name, null: false
t.string :image, null: false
t.text :description
t.timestamps
end
end
end

我的种子.rb

p1 = Planet.create(name: "Sun", image: "/../assets/images/sun.jpg")
p1.description.push("The center of the solar system and the only star in solar system.", 
"Due to its huge mass, other planets in solar system form radiant power between sun and itself, maintaining the rotation around sun", 
"The surface temperature is said to be about 6000 degree celcius.")
p1.save

我的星球类

class Planet < ApplicationRecord
serialize :description, Array
end

Rails 提供了一种创建数组类型列的方法,但 ActiveRecord 仅支持 PostgreSQL 数组列,它不适用于 mysql2 db 所以,我遇到了同样的情况,我通过序列化列来做到这一点(通过这样做,您独立于数据库依赖关系。

1-创建类型为text的列(如果是上次迁移,则创建db:rollback列(

t.text :description

2-Planet模型中

serialize :description, Array

3 -

p1 = Planet.new(name: "Sun", image: "/../assets/images/sun.jpg")
p1.description.push("The center of the solar system and the only star in solar system.", "Due to its huge mass, other planets in solar system form radiant power between sun and itself, maintaining the rotation around sun","The surface temperature is said to be about 6000 degree celcius.")
p1.save

4-现在您可以浏览每个描述,它将被视为数组而不是字符串

<%unless @planet.blank?%>
<h1><%= @planet.name %></h1>
<%= image_tag @planet.image %>
<ul>
<%unless @planet.description.blank?%>
<% @planet.description.each do |x| %>
<li><%= x %></li>
<% end %>
<%end%>
</ul>
<%end%>

相关内容

最新更新