0

I cant understand my this is not working. I am trying to add a method to create a slug from the title of a page when the user creates a new page (using Ruby on Rails).

This is my create method:

  def create
@page = Page.new(params[:page])
@page.user_id = current_user.id
@page.slug = @page.title.to_slug

respond_to do |format|
  if @page.save
    format.html { redirect_to @page, notice: 'Page was successfully created.' }
    format.json { render json: @page, status: :created, location: @page }
  else
    format.html { render action: "new" }
    format.json { render json: @page.errors, status: :unprocessable_entity }
  end
end

end

Adn this is my method at the bottom of the same same controller. (pages_controller.rb) :

    def to_slug(param=self.slug)

    # strip the string
    ret = param.strip

    #blow away apostrophes
    ret.gsub! /['`]/, ""

    # @ --> at, and & --> and
    ret.gsub! /\s*@\s*/, " at "
    ret.gsub! /\s*&\s*/, " and "

    # replace all non alphanumeric, periods with dash
    ret.gsub! /\s*[^A-Za-z0-9\.]\s*/, '-'

    # replace underscore with dash
    ret.gsub! /[-_]{2,}/, '-'

    # convert double dashes to single
    ret.gsub! /-+/, "-"

    # strip off leading/trailing dash
    ret.gsub! /\A[-\.]+|[-\.]+\z/, ""

    ret
  end

The slug method is from this question: Best way to generate slugs (human-readable IDs) in Rails

I cant understand why this creates a method undefined error or how to fix it. Any help, hint or answer is appreciated. :)

Community
  • 1
  • 1
Ole Henrik Skogstrøm
  • 6,353
  • 10
  • 57
  • 89

1 Answers1

1

The to_slug method is an instance method of PagesController class. The object @page.title don't have this method, that's the reason why the code not working.

There are several ways to make the method to_slug work, such as helper, decorate. But I think the best way is to put such logic into model, because slug is actually part of the model. We'll make slug attribute available instantly before saving(create and update).

So, in Page model. Assume you already have slug attribute.

Step 1: Setup callback

before_saving :update_slug  # for create record, before actual saving

Step 2: update_slug method

def update_slug  
  ret = self.title # Use title variable directly
  # .... You to_slug code. Almost same.
  self.slug = ret # return slug
end

The above are basic ideas to provide a thought, not verified yet. Please check and verify it by yourself. Hope that helps.

Billy Chan
  • 24,625
  • 4
  • 52
  • 68