问题
Using Rails 4.2, I want to create a custom route using an attr_accessor rather than a table column, but I can't get the resource_path method to work.
I want custom route like this: /foos/the-title-parameterized-1 (where "1" is the id of the object).
Foo model:
#...
attr_accessor :slug
#dynamically generate a slug:
def slug
"#{self.title.parameterize[0..200]}-#{self.id}"
end
#...
routes.rb:
get 'foos/:slug' => 'foos#show', :as => 'foo'
foos_controller.rb:
def show
@foo = Foo.find params[:slug].split("-").last.to_i
end
In my show view, when I use helper method foo_path it returns the route using the id of the object rather than the slug like this: /foos/1. Is it possible to get this helper method to use the accessor method? Am I off track with this approach?
I would prefer to use Friendly Id but I dont believe its possible without creating a slug column in my model table. I dont want to create a column because there are millions of records.
回答1:
You want to override the to_param method in your model:
class Foo < ActiveRecord::Base
# ...
def to_param
slug
end
# or
alias :to_param :slug
end
You may also want to use the :constraints option in your route so that only URLs that match e.g. /-\d+\z/ are matched.
Keep in mind also that, using this method, the path /foos/i-am-not-this-foos-slug-123 will lead to the same record as /foos/i-am-this-foos-slug-123.
来源:https://stackoverflow.com/questions/41658221/rails-routing-using-custom-attribute-rather-than-table-column