Reputation: 13
Let's say I have Pet
s and Cat
s. Cats are stored in the pets
table with the value 'Cat' in the type
column.
Let's say I create a link like this:
link_to 'My Pet', Pet.find(1)
This will generate a link using the pet_path
as expected.
But then let's say I create a link like this:
link_to 'My Pet', Cat.find(1)
This will generate a link using the 'cat_path', which is smart, but not what I want because I only have/need a PetController.
Clearly, I can just use pet_path(Cat.find(1))
in the link_to, but I'm wondering if there is a more robust solution. What if I have Dogs, Birds, etc.? I don't want to have to remember to explicitly use pet_path
every time.
How can I make sure that the second link will create a link with the pet_path
moving forward? Is there a setting on the Cat model or the Pet model or something I can put in routes.rb to ensure this?
-edit-
There's some confusion over what I'm trying to achieve. I simply want to know how to make sure that a call to link_to with a Cat object will resolve to a pet_path instead of a cat_path. I'm not looking for a way to change how my table is set up. In an ideal situation, I wouldn't have to create a bunch of controllers for the different pet types either. I'd like to know whether there is a simple, elegant way to tell Rails to use the parent class for a model when determining the url helper.
Upvotes: 1
Views: 71
Reputation: 36860
You could create custom routes either manually
get 'cats/:id' => 'pets#show'
put 'cats/:id' => 'pets#update'
delete 'cats/:id' => 'pets#destroy'
# etc etc
...
or using resources
resources :cats, controller: 'pet'
Slightly outside the scope of your question, but the create action could test the url request.original_url
and know what kind of pet to create based on what path was called with the POST
command.
Upvotes: 0