public
Description: Rails plugin that adds a from_param class method to ActiveRecord::Base for simple URL-based fetching.
Homepage: http://mbleigh.lighthouseapp.com/projects/10478-from-param
Clone URL: git://github.com/mbleigh/from_param.git
mbleigh (author)
Tue Apr 29 06:20:29 -0700 2008
commit  75ad9389aa1766348e8ce98aa3471359217c1457
tree    077086a509089a66f45147344541dcbc72870b68
parent  0317cb7e6e089d3bfd18546a353fc577c232a4b0
from_param / README
100644 58 lines (44 sloc) 2.085 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
FromParam
=========
 
This plugin is an addition to ActiveRecord::Base that establishes a better
convention for finding records based on parameters. It adds a "from_param" class
method to ActiveRecord::Base as a convention for fetching a model from a URL
parameter. By default it will find a record based on the to_i of the passed in
parameter, but storing a parameter in a column is where it becomes especially useful.
 
If you create a 'param' column in your table (or any other column using set_param_column),
the to_param of your record will automatically be saved to that column whenever
you save the record, and you will be able to retrieve it using just a simple
Model.from_param call with the generated to_param. It is probably wise to add an index
to the param column if you use one.
 
It's time to move away from generated-key-dependence, and this plugin is an attempt
to make that easy, painless, and work easily within the existing systems.
 
Example
=======
 
  # default behavior
 
  class User < ActiveRecord::Base
    def to_param
      "#{id}-#{first_name.downcase}-#{last_name.downcase}"
    end
  end
  
  class UsersController < ApplicationController
    # GET /users/1-bobby-mcfarin
    def show
      @user = User.from_param(params[:id]) # => <User id=1 first_name="Bobby" last_name="McFarin">
    end
  end
  
  # using a 'param' column, in this case 'slug'
  
  class Post < ActiveRecord::Base
    set_param_column "slug" # defaults to "param"
    def to_param
      "#{created_at.strftime("%Y-%m-%d")}-#{title.gsub(" ","-").downcase.gsub(/[^a-z0-9-]/,"")}"
    end
  end
 
  class PostsController < ApplicationController
    # GET /posts/2008-04-26-from-param-plugin-released
    @post = Post.from_param(params[:id]) # => <Post title="From Param: Plugin Released" created_at="2008-04-26">
  end
  
Resources
=========
 
GitHub: http://github.com/mbleigh/from_param
Lighthouse: http://mbleigh.lighthouseapp.com/projects/10478-from-param
 
Copyright (c) 2007 Michael Bleigh (http://mbleigh.com/) and Intridea Inc. (http://intridea.com/), released under the MIT license