I can’t seem to set up a custom URL. All the RESTful routes work fine, but I can’t figure out how to simply add /:unique_url to the existing routes, which I create in the model (a simple 4 character random string) and will serve as the “permalink” of sorts.
Routes.rb
resources :treks
match ':unique_url' => 'treks#mobile'
Controller
.
.
def mobile
@trek = trek.find(params[:id])
end
Is this because I’m trying to define a custom action on an existing resource? Can I not create custom methods on the same controller as one with a resource?
By the way, when I change routes.rb to match 'treks/:id/:unique_url' => treks#mobile it works fine, but I just want the url to simply be /:unique_url
Update It seems like find_by_[parameter] is the way to go…
I’ve been playing in console and I can’t seem to get any methods to come forward…I can run Trek.last.fullname for example, but cannot run @trek = Trek.last…and then call…@trek.lastname for example. Any clues why? I think this is my issue.
@pruett no, the
find_by_XXXmethods are generated on-the-fly via Ruby’s method_missing call! So instead of XXX you can use any of the attributes which you defined in a model.You can even go as far as listing multiple attributes, such as:
Check these pages:
http://guides.rubyonrails.org/active_record_querying.html
http://m.onkey.org/active-record-query-interface
if you get a
undefined method ... for nil:NilClass, it means that the object you are trying to call that method on does not exist, e.g. is nil.You probably just missed to put an if-statement before that line to make sure the object is non-nil