views:

35

answers:

1

Given a model like:

class PhoneNumber < ActiveRecord::Base
  has_many :personal_phone_numbers
  has_many :household_phone_numbers
  has_many :organization_phones

  has_many :people, :through => :personal_phone_numbers
  has_many :households, :through => :household_phone_numbers
  has_many :organizations, :through => :organization_phones
end

When viewing a phone number, I'm probably going to be viewing it as a nested resource, so the controller is going to have a params item of one of person_id, household_id, or organization_id

I need the view to have a link_to "Return", ... that returns to the correct resource that we came to the phone number from. How should I do this?

+1  A: 

If you're using nested resources, you'll need a before filter on your PhoneNumberController that sets the parent object, so you can do @parent.phone_numbers.build(...) right? At the same time (before_filter), set the @parent_path (organization_path, household_path...) and you'll have that available in your view to link to.

If you were adding the phone number to each of these things (organization, household...) using :polymorphic => true instead of has_many :through, you could simply take the @parent that you'll be setting in the PhoneNumbersController before_filter and do polymorphic_path(@parent) instead.

Ben
If @parent is set in the controller and you have restful routes, you can just do `link_to "Return", @parent`
mckeed
Actually, I didn't realize what magic polymorphic_url did. In my view, all I have to do is `link_to "Return", @parent` and it magically knows what resource to go back to.
DGM