howto find_by ownkey the exact entry in rails - ruby-on-rails

we have an show-action which should find by the own_key the right entry. The own_key is generated as UUIDTools::UUID.timestamp_create().to_s.
The following question is now here.
class ListController < ApplicationController
respond_to :html, :xml, :json
def show
#list = List.find_by_own_key(params[:own_key])
respond_with(#list)
end
end
the routes are here so generates
resources :lists
match '/:id' => 'list#show'
why did we get also an entry back if we only type one simple letter after the /?
The own_key look so f6d47c20-a276-11e1-b127-68a3c454c2b4. So if we type an /lists/f i get the entry with an f own_key. how can we manage that we only get the entry with the own_key?
Could it run by an contraint?
thanks for the help if anone can help us?
Marcus

From your routes, params[:id] will contain the I'd to search for, however you're using params[:own_key] which will be nil. Instead of searching for the record with the specified value of own_key your code will always fetch the row with a null own_key.
Change your code to use params[:id] and you should be ok

U can use constrainsts for route or check params[:own_key] in controller
:constraints => {:own_key=> /regexp pattern for uuid/}

Related

Rails getting routes name in Route.rb with controller actions

I'm a real beginner of rails.
Can I get multiple routes from one controller + many actions?
For example,
resources :something
get "something#index", "something#show", "something#update"...etc.
I'm just curious if there is a command to get route name from the actions.
For example, in a controller named "pledges",
class PledgesController < ApplicationController
def home
end
def abc
end
def defg
end
def hijk
end
end
Can any commands get "pledges#home", "pledges#abc", "pledges#defg","pledges#hijk" ?
To add custom, "non-RESTful" routes to a resource, you could do the following:
resources :pledges do
collection do
get :foo
end
member do
put :bar
end
end
collection-defined routes will produce results against Pledge as a whole – think the index route.
member-defined routes will produce results against an instance of Pledge – think the show route.
This would produce the following routes for you:
foo_pledges GET /pledges/foo(.:format pledges#foo
bar_pledge PUT /pledges/:id/bar(.:format) pledges#bar
pledges GET /pledges(.:format) pledges#index
POST /pledges(.:format) pledges#create
new_pledge GET /pledges/new(.:format) pledges#new
edit_pledge GET /pledges/:id/edit(.:format) pledges#edit
pledge GET /pledges/:id(.:format) pledges#show
PATCH /pledges/:id(.:format) pledges#update
PUT /pledges/:id(.:format) pledges#update
DELETE /pledges/:id(.:format) pledges#destroy
You will have to define all of the custom actions, if there are not restful (but I would highly recommend that you follow the rest conventions). For example:
get 'pledges' => 'abc'
post 'pledges' => 'defg'
put 'pledges' => 'hijk

Rails4 new template .erb creation Not Happening

I have generated scaffold and created a view called "appointment"
I wanted to added a template .erb file called inbox_mail.html.erb in appointment folder.
I did setting like this.
route.rb
get '/appointments/inbox_mail'
In appointment controller
class AppointmentsController < ApplicationController
def inbox_mail
end
end
Now running the link 3000/appointments/inbox_mail
but giving rise error as,
Mongoid::Errors::DocumentNotFound in AppointmentsController#show
Problem: Document(s) not found for class Appointment with id(s) delete_appointment. Summary: When calling Appointment.find with an id or array of ids, each parameter must match a document in the database or this error will be raised. The search was for the id(s): delete_appointment ... (1 total) and the following ids were not found: delete_appointment. Resolution: Search for an id that is in the database or set the Mongoid.raise_not_found_error configuration option to false, which will cause a nil to be returned instead of raising this error when searching for a single id, or only the matched documents when searching for multiples.
Help me in Rails4...!!!!
May be this is b'z of
def set_appointment
#appointment = Appointment.find(params[:id])
end
Yes, it is because of set_appointment method. I guess you should add :id segment to your route, like
match '/appointments/delete_appointment/:id', to: 'appointments#delete_appointment', via: :get
and this should work.
Delete something shouldn't be done through GET, you should use the DELETE method. So, when you create the link with "link_to" you should do:
link_to 'Delete appointment', delete_appointment_path(#appointment.id), method: :delete
you need a route like:
delete '/appointments/delete_appointment/:id', to: 'appointments#delete_appointment'
Then rails will take care of that and do a DELETE request with the appointment's id, then on your controller you can use #appointment = Appointment.find(params[:id])
You may want some kind of validation to render a "not found" template:
def delete_appointment
unless #appointment = Appointment.find(params[:id])
redirect_to appointment_not_found_path #something_like_that
end
end
EDIT: it looks like some before_filter is messing up there too, you talked about "delete_appointment", the error say the action called is "show" and you copied the code for the action/before_filter "set_appointment", check that first
EDIT 2: you say you are not doing any delete, then use get, the important part is the :id on the url if you need to find an appointment by an ID you need that on the url. If you don't need the ID then check your before filters, I guess you have something like
before_filter :set_appointment
you may want to skip that filter on delete_appointment
before_filter :set_appointment, except: :delete_appointment

How to use another attribute of a Rails resource in the URL?

I am trying to follow http://railscasts.com/episodes/63-model-name-in-url to achieve URLs that look like:
/dog/<custom field of dog>
instead of
/dog/1
Where "1" is the internal primary key of the Dogs table. The custom field I want happens to be another integer in the Dogs field.
My code:
dogs_controller.rb:
load_and_authorize_resource :except => [:index]
def show
Rails.logger.info("Hello")
#dog = Dog.find_by_custom_field(params[:id])
end
dog.rb:
def to_param
custom_field
end
In particular, when I try to load /dogs/<custom_field>, it still insists on using that integer as the primary key lookup, instead of looking up on the custom field. So I get a Couldn't find Dog with id=<custom_field>. error
Interestingly, the logger line also never gets printed when I try to do this. However, when I remove the load_and_authorize_resource (CanCan) line, then it works. What is going on here?
for using a different attribute other than id pass :find_by option
load_and_authorize_resource :except => [:index] , :find_by => :custom # will use find_by_custom!(params[:id])
for more info read cancan manual for controller methods
http://rdoc.info/github/ryanb/cancan/master/CanCan/ControllerAdditions/ClassMethods

Ruby on Rails how does this route not work

In my config > routes I have:
#Service Routes
match "services" => "services#index"
match "startsingleservice" => "services#start_single_service"
match "stopsingleservice" => "services#stop_single_service"
match "zookeeperreindex" => "services#show_zookeeper"
The first 3 work, no issues no problems. And all four are in the same file def/functions whatever you wanna call them. Are in the same file. Where again first 3, work awesome. Adding that new guy there, zookeeper just doesn't wanna work I get
Unknown action
The action 'show_zookeeper' could not be found for ServicesController
the function zookeeperreindex is almost a mirror of the actual index def in the same file, changed for the needs of redisplay as I only want a JSON output for that one. But bottom line is I changed the routes to match, I know the function is working for the most part, and I am not seeing where I could be messing this simplicity up, I've also restarted the server itself to ensure it wasn't that
Edit
In replying with code from the controller which by the way did "show_zookeeper" defined right.. I realized I had a misplaced "end" tag.. So, in moving that the route worked.
It looks like in your ServicesController (app/controllers/services_controller.rb)
You never define a method show_zookeeper. My guess is that you define a method zookeeperreindex instead of show_zookeeper.
Why don't you link the contents of that file? You should see something along the lines of,
class ServicesController < ActionController::Base
def index
...
end
def start_single_service
...
end
def stop_single_service
...
end
def show_zookeeper # <---- This one is missing
end
end
The way the routes work the part after the => determines the controller and action. For example "services#start_single_service" will be mapped to :controller => ServicesController, and :action => start_single_service.
Thus the final call will be ServicesController.start_single_service
Look at http://guides.rubyonrails.org/routing.html for more info

Accessing a resource in routes.rb by using attributes other than Id

I have the following in my routes.rb
map.resources :novels do |novel|
novel.resources :chapters
end
With the above defined route, I can access the chapters by using xxxxx.com/novels/:id/chapters/:id.
But this is not what I want, the Chapter model has another field called number (which corresponds to chapter number). I want to access each chapter through an URL which is something like
xxxx.com/novels/:novel_id/chapters/:chapter_number. How can I accomplish this without explicitly defining a named route?
Right now I'm doing this by using the following named route defined ABOVE map.resources :novels
map.chapter_no 'novels/:novel_id/chapters/:chapter_no', :controller => 'chapters', :action => 'show'
Thanks.
:id can be almost anything you want. So, leave the routing config untouched and change your action from
class ChaptersControllers
def show
#chapter = Chapter.find(params[:id])
end
end
to (assuming the field you want to search for is called :chapter_no)
class ChaptersControllers
def show
#chapter = Chapter.find_by_chapter_no!(params[:id])
end
end
Also note:
I'm using the bang! finder version (find_by_chapter_no! instead of find_by_chapter_no) to simulate the default find behavior
The field you are searching should have a database index for better performances

Resources