GeorgieF
GeorgieF

Reputation: 2737

Understanding to_param from_param

I have a Rails 3 simple scaffolded application having one model like that:

class Contact < ActiveRecord::Base
  def to_param
    self.firstname
  end

  def self.from_param param
    self.where(firstname: param).first
  end
end

As far as I have read about from_param, everything should work as if to_param was never defined. But it does not work. Rails is still issuing this SQL:

SELECT "contacts".* FROM "contacts" WHERE "contacts"."id" = 0 LIMIT 1

when I try to show/edit the first entry.

I wonder if from_param has any effect at all? This post as well as many others seem to state that. I am unable to get this working.

What am I doing wrong? Thx for any answer. Felix

Upvotes: 2

Views: 1777

Answers (1)

Jonathan del Strother
Jonathan del Strother

Reputation: 2572

Rails doesn't know anything about from_param - that blog post is manually calling it ( Model.from_param(params[:id]) ). If you're just calling Contact.find('fred'), that won't work, it's going to convert 'fred' to an integer (0), and search for that id.

Upvotes: 2

Related Questions