Polymorphic controller and caller
I have a polymorphic link to an address that can be either member owned or dependent. Everything looked great until I realized that I didn't know what type of object was creating it unless I miss something. Is there a way to tell the routing file to include the object type?
Models:
class Member < ActiveRecord::Base
has_one :address, as: :person, dependent: :destroy
end
class Dependent < ActiveRecord::Base
has_one :address, as: :person, dependent: :destroy
end
class Address < ActiveRecord::Base
belongs_to :person, polymorphic: true
end
Controller:
def new
@person = ???
@address = Address.new(person: @person)
end
Routes currently:
resources :members do
resources :addresses, shallow: true
resources :dependents, shallow: true do
resources :addresses, shallow: true
end
end
I have routes for the address under each, but I will need to check the parameters [: member_id] or params [: dependent_id]. What happens when I attach notes to everything. I probably missed some easy way to do this in Rails, any advice would be greatly appreciated!
source to share
Basically you want to set the person object before creating the address. You can do it in your address controller like this:
In the address controller:
class AddressesController < ApplicationController
before_action :set_person
def new
@address = @person.build_address
end
def set_person
klass = [Member, Dependent].detect{|c| params["#{c.name.underscore}_id"]}
@person= klass.find(params["#{klass.name.underscore}_id"])
end
end
Regarding your routes file, currently according to the relationships you defined in your models, it should work:
resources :members do
resource :address #singular resource routing as its a has_one relationship
end
resources :dependents do
resource :address #singular resource routing as its a has_one relationship
end
(Note that I used special routing for the nested resource. You can read more here: http://guides.rubyonrails.org/routing.html#singular-resources )
source to share