S.BM
S.BM

Reputation: 127

render array in view with Ruby

I'm new to Ruby and I try to render an array which is in a separate file called database.rb:

Data = [
  {
    title: "First",
    content: "Lorem ipsum...",
    photo: "image1"
  },
  {
    title: "Second",
    content: "Eventually ...",
    photo: "image2"
  },
  {
    title: "Third",
    content: "also to Kim’s ....",
   photo: "image3"
  }
]

I now want to render this array in a view.

In my app.rb I have this code:

require "sinatra"
require "sinatra/activerecord"

require_relative "database"

["/", "/articles"].each do |path|
  get path do
      @database = Data
    erb :index
  end
end

In my view index:

<% @database.each do |article| %>

    <!-- Blog Post -->
    <div class="card mb-4">
      <img class="card-img-top" src="<%= article.photo %>" alt="">
      <div class="card-body">
        <h2 class="card-title oink"><%= article.title %></h2>
        <p class="card-text oink"><%= article.content %></p>
      </div>
      <div class="card-footer text-muted">
      </div>
    </div>

  <% end %>

How to get this to work? Because it seems that properties title, content and photo are not recognized. What I should do? creating a model? but how?

Upvotes: 2

Views: 203

Answers (1)

Ursus
Ursus

Reputation: 30071

Your array is made of hash items. If you want to stick with hashes, this is the way to access values (by key)

<!-- Blog Post -->
<div class="card mb-4">
  <img class="card-img-top" src="<%= article[:photo] %>" alt="">
  <div class="card-body">
    <h2 class="card-title oink"><%= article[:title] %></h2>
    <p class="card-text oink"><%= article[:content] %></p>
  </div>
  <div class="card-footer text-muted">
  </div>
</div>

Otherwise, if you want to have methods, you might use Ruby Struct

Article = Struct.new(:title, :content, :photo)

Data = [
  Article.new("First", "Lorem ipsum...", "image1"),
  Article.new("Second", "Eventually ...", "image2"),
  Article.new("Third", "also to Kim’s ....", "image3")
]

Now you can do it like in your snippet

Upvotes: 3

Related Questions