0
votes

I'm following a tutorial on how to build a blogging website based on Ruby on Rails. At the moment an article looks like below:

Article 4

The article has a title, a body, and comments below. The fields in which you enter your name and comment are currently entitled "AUTHOR NAME" and "BODY", respectively. These are 'default' names based on their corresponding attributes; see comments_controller.rb below.

class CommentsController < ApplicationController
  def create
    @comment = Comment.new(comment_params)
    @comment.article_id = params[:article_id]
    @comment.save
    redirect_to article_path(@comment.article)
  end

  def comment_params
    params.require(:comment).permit(:author_name, :body)
  end

end

The question is how to change the labels "AUTHOR NAME" and "BODY" into the custom labels "Your name" and "Your comment". The article is rendered by the view show.html.erb:

<h1><%= @article.title %></h1>
<p><%= @article.body %></p>
<h3>Comments (<%= @article.comments.size %>)</h3>
<%= render partial: 'articles/comment', collection: @article.comments %>
<%= render partial: 'comments/form' %>
<%= link_to "<< Back to Articles List", articles_path %>
<%= link_to "delete", article_path(@article), method: :delete, data: {confirm: "Really delete the article?"} %>
<%= link_to "edit", edit_article_path(@article) %>

The display of the form is governed by the partial _form.html.erb:

<%= form_for(@article) do |f| %>
  <ul>
  <% @article.errors.full_messages.each do |error| %>
    <li><%= error %></li>
  <% end %>
  </ul>
  <p>
    <%= f.label :title %><br />
    <!-- <%= f.label :author_name, "Your name" %><br /> -->
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :body %><br />
    <!-- <%= f.label :author_name, "Your Name"  %> -->
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>

I've tried to implement the customized label using the commented-out lines, but this didn't work. How can I customize the labels?

2
When you used the commented out code, I assume you commented out the existing f.label lines? Also when you tried it, what happened? Did you still get the old labels? Something else? What went wrong? - lurker
Sorry for asking but, if my answer solved your question please mark it as accepted answer :-) - Alex

2 Answers

4
votes

Just do:

<%= f.label "Your name" %>
<%= f.text_field :title %>

<%= f.label "Your comment" %>
<%= f.text_area :body %>

The way you are doing it sets the label to what :title and :body correspond to in the model.

0
votes

I would still keep the :title and :body on the form, but would add the custom label as second parameter.

<p>
    <%= f.label :title, "Your name" %><br />
    <%= f.text_field :title %>
</p>
<p>
    <%= f.label :body, "Your custom label" %><br />
    <%= f.text_area :body %>
</p>