开发者

Rails - Capitalize Article Tags and Titles

Am trying to find a way of capitalizing the 1st letter of all Titles and Tags when a user submits a开发者_Go百科n article. I can use the capitalize method, but where do I add it to the controller code blocks for it to work?

Thx

controllers/articles_controller:

def new
  @article = Article.new

  respond_to do |format|
   format.html # new.html.erb
   format.xml  { render :xml => @article }
 end
end

controllers/tags_controller:

class TagsController < ApplicationController
    def show
      @tag = Tag.find(params[:id])
    @articles = @tag.articles
  end
end

models/article:

def tag_names
  @tag_names || tags.map(&:name).join(' ')
end

private

def assign_tags
  if @tag_names
    self.tags = @tag_names.split(/\,/).map do |name|
    Tag.find_or_create_by_name(name)
    end
  end
 ...


Where do you plan to capitalize it? before saving in the database? or when you're showing it to the user?

There are two ways to this:

Use rail's titleize function or capitalize

or do it using CSS with:

 <p class="tag">im a tag</p>

 #CSS
 .tag {
   text-transform:capitalize;
 }


I would do something like this to force them to be capitalized before saving.

class Article < ActiveRecord::Base
  def title=(title)
    write_attribute(:title, title.titleize)
  end

  private

  def assign_tags
    if @tag_names
      self.tags = @tag_names.split(/\,/).map do |name|
        Tag.find_or_create_by_name(name.capitalize)
      end
    end
  end
end


Try to use .capitalize

e.g. "title".capitalize will make "Title"


As Francis said, use .capitalize in your controller

I use this

@article= Article.new(params[:article])
@article.name = @article.title.capitalize 
@article.save
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜