Polymorphic controller and calling object

2019-03-31 14:22发布

问题:

I have a polymorphic relationship with address being able to both be owned by a member or a dependent. Everything looked great until I realized that I wouldn't know what type of object was creating it unless I'm missing something. Is there a way to tell the routing file to include the type of object?

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 to address under each but would need to check for params[:member_id] or params[:dependent_id] I think. What happens when I attach notes to everything. I'm probably missing some easy way to do this in Rails, any advice would be greatly appreciated!

回答1:

Basically you want to set the person object before creating a address. You can do this in your address controller like this:

In your 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

As for your routes file, currently according to the relationships that you have defined in your models the following 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

(Notice that I have used singular routing for nested resource. You can read more on it here : http://guides.rubyonrails.org/routing.html#singular-resources)