khpeek khpeek - 5 months ago 9
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

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?

Answer

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.

Comments