2

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

thankx a lot. it works. but what if I choose to work with models ?
You can even add methods to this structs. Anyway, if you want to have models you probably should pick up some ruby package for that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.