khpeek khpeek - 2 years ago 58
Ruby Question

Create a custom label

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


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

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


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

<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_for(@article) do |f| %>
<% @article.errors.full_messages.each do |error| %>
<li><%= error %></li>
<% end %>
<%= f.label :title %><br />
<!-- <%= f.label :author_name, "Your name" %><br /> -->
<%= f.text_field :title %>
<%= f.label :body %><br />
<!-- <%= f.label :author_name, "Your Name" %> -->
<%= f.text_area :body %>
<%= f.submit %>
<% 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download