Неопределенный метод Ruby on Rails `each 'для #ошибка - PullRequest
0 голосов
/ 05 июня 2018

Я пытался просмотреть строковый массив в html, но получил ошибку "undefined method` each 'for # ". Изображение ошибки

Вот определение класса для класса Планета

 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>

Вот как я мигрировалit

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

My seed.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

Класс My Planet

class Planet < ApplicationRecord
    serialize :description, Array
end

1 Ответ

0 голосов
/ 05 июня 2018

Rails предоставляет способ создания столбца типа массива, но ActiveRecord поддерживает только столбцы массива PostgreSQL, он не будет работать с mysql2 db, поэтому я столкнулся с той же ситуацией, и я сделал это с помощью serialize столбец (выполняя это, вы не зависите от зависимости от базы данных.)

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%>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...