DGM
DGM

Reputation: 26979

finding parent of nested resource that has multiple types of parents

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?

Upvotes: 0

Views: 272

Answers (1)

Ben
Ben

Reputation: 6967

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.

Upvotes: 1

Related Questions