michaelsking1993
michaelsking1993

Reputation: 441

Joining on new line: displaying on new line

(edit: I've temporarily fixed this by simply placing it in a table, but I'd like to do cool things with each line styling wise and I feel like I'll be restricted with a table)

I'd like to display an array of strings in a view page with each string on its own new line. I have a Story model with columns for title and author_id, and a StoryLine model with columns for story_line, line_index, and story_id (my question does not concern this data structure - I'm confident that this is the right move for my use case). The story text consists of many lines without periods that are split on new lines, so when the text gets inputted, I parse them into the database in the create action as follows:

story_lines = params[:story_text].split("\n")
    story_lines.each do |line|
      @story_line = @story.story_lines.build
      index = story_lines.index(line)
      @story_line.line_index = index
      @story_line.story_line = line
      @story_line.save!
    end

When a story gets opened by a user, all the story_lines get displayed in order of their index through the following code in the show action of the controller: @story_lines = @story.story_lines.order(:line_index).pluck(:story_line).join("\r\n")

They then get displayed in the view as follows: <%= @story_lines %>

However, for as many different methods as I've tried of changing this around in my controller and view, it's not displaying them on new lines. It's joining them successfully and in the correct order, but each sentence bumps up right up against the next one, with literally zero spaces inbetween the last word of one sentence and the first word of the next sentence.

Any ideas on how I should do this? I'm almost positive that I could do it by putting each newline in its own row of a table, but this seems like a cheap workaround for something that should be able to be handled with a <br />

Upvotes: 0

Views: 509

Answers (1)

Taryn East
Taryn East

Reputation: 27747

What you need is more/better html :)

The problem is not rails - but the fact that this is what happens in a browser when you pump out a whole bunch of text.

If you want newlines to appear in html - then you need to use something that adds breaking-space.

You could use <br> for that (which is literally what br stands for) or you could use paragraphs eg:

<p> <!-- text should always be put inside a block-level object eg a paragraph -->
  <% @story_lines.each do |line| %>
    <%= line %><br> <!-- br example -->
  <% end %>
</p>

<% @story_lines.each do |line| %>
  <p><%= line %></p> <!-- p example -->
<% end %>

Obviously only choose one or the other or it'll be duplicated. :)

Upvotes: 1

Related Questions