【问题标题】:Polymorphic controller and calling object多态控制器和调用对象
【发布时间】:2014-12-06 18:26:04
【问题描述】:

我与 address 具有多态关系,既可以由成员拥有,也可以由受抚养人拥有。一切看起来都很棒,直到我意识到我不知道创建它的是什么类型的对象,除非我错过了一些东西。有没有办法告诉路由文件包含对象的类型?

型号:

 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

控制器:

 def new
  @person = ???
  @address = Address.new(person: @person)
 end

当前路线:

  resources :members do
    resources :addresses, shallow: true
    resources :dependents, shallow: true do
      resources :addresses, shallow: true
    end
  end

我在每个路由下都有地址,但我认为需要检查 params[:member_id] 或 params[:dependent_id]。当我在所有内容上附加注释时会发生什么。我可能错过了在 Rails 中执行此操作的一些简单方法,任何建议将不胜感激!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 routes polymorphic-associations


    【解决方案1】:

    基本上,您希望在创建地址之前设置人员对象。您可以像这样在地址控制器中执行此操作:

    在您的地址控制器中:

    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
    

    至于您的路线文件,目前根据您在模型中定义的关系,以下应该可以工作:

    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
    

    (请注意,我对嵌套资源使用了单数路由。您可以在此处阅读更多信息:http://guides.rubyonrails.org/routing.html#singular-resources

    【讨论】:

      猜你喜欢
      • 2020-08-22
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多