ubique
ubique

Reputation: 1212

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 an 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
 ...

Upvotes: 2

Views: 1428

Answers (4)

Austin Taylor
Austin Taylor

Reputation: 5477

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

Upvotes: 2

Nick
Nick

Reputation: 1325

As Francis said, use .capitalize in your controller

I use this

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

Upvotes: 0

corroded
corroded

Reputation: 21564

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;
 }

Upvotes: 3

Francis Gilbert
Francis Gilbert

Reputation: 3442

Try to use .capitalize

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

Upvotes: 0

Related Questions