1

Good night. I'm doing the getting started guide of RoR, but I have a trouble: When I click the New Article button that redirects to the form, Rails throw an 'Encountered a syntax error while rendering template.' The new.html.erb code is

<h1>New Article</h1>

<%= form_with scope: :article, url: articles_path, local: true do |form| %>

<%= if @article.errors.any? %>
    <div id="error_explanation">
        <h2>
            <%= pluralize(@article.errors.count, "error") %>
            prohibited this article from being saved:
        </h2>
        <ul>
            <% @article.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
        </ul>
    </div>
<% end %>

    <P>
        <%= form.label :title %><br>
        <%= form.text_field :title %>
    </p>

    <p>
        <%= form.label :text %><br>
        <%= form.text_area :text %>
    </p>

    <p>
        <%= form.submit %>
    </p>
<% end %>

<%= link_to 'Back', articles_path %>

The code is the same as the guide's code, so i don't know where the error or errors can be. I also attach the error screenshot if it's any help. Rails error message when I want tho create a new Article

Erik Garcia Rosa
  • 59
  • 1
  • 2
  • 10
  • Looking at your screenshot, I think the problem is the `\n`. Did you copy/paste this code to your environment? – Cannon Moyer Dec 29 '19 at 22:16
  • That syntax error should include a "stack trace", showing the filepaths and line numbers that were executed leading up to the error. The top of the trace is the last line executed, and generally the problem line. Could you include that stack trace as well as indicate the lines in your code example? – steel Dec 29 '19 at 22:24

1 Answers1

2

Here two problems:

  • wrong syntax in if condition (don't need to use =)

  • extra \n chars in your screenshot

Change your 5 line in app/view/articles/new.html.erb to:

<% if @article.errors.any? %>

<% %> executes Ruby code

<%= %> executes Ruby code and prints out

Also read about the difference on SO

mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • *wrong syntax in `if` condition (don't need to use `=`)* I wouldn't call this wrong in the sense that the syntax is valid. It's possible for an `if` expression to return something that one would be interested in. In this case, the OP did not intend that (your comment, *didn't need to use*, is accurate). But it's still valid syntax. – lurker Dec 29 '19 at 22:49
  • @lurker you are right. But it's specific answer to specific question. In this context it's wrong. That's why syntax error occurred – mechnicov Dec 29 '19 at 23:11