创建自定义标签

时间:2016-06-20 15:02:41

标签: html ruby-on-rails ruby

我正在关注如何基于Ruby on Rails构建博客网站tutorial。目前文章如下:

Article 4

这篇文章的标题,正文和评论如下。您输入姓名和评论的字段目前分别名为“AUTHOR NAME”和“BODY”。这些是基于其相应属性的“默认”名称;请参阅下面的comments_controller.rb

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

问题是如何将标签“AUTHOR NAME”和“BODY”更改为自定义标签“Your name”和“Your comment”。该文章由视图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) %>

表单的显示由部分_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 %>

我尝试使用注释掉的行来实现自定义标签,但这不起作用。如何自定义标签?

2 个答案:

答案 0 :(得分:3)

只是做:

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

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

您采用的方式将标签设置为模型中:title :body 对应的标签。

答案 1 :(得分:0)

我仍然会在表单上保留:title和:body,但会将自定义标签添加为第二个参数。

<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>
相关问题