Polymorphic controller and calling object

给你一囗甜甜゛ 提交于 2019-12-03 20:14:24

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!