我与地址具有多态关系,地址既可以由成员也可以由属拥有.一切看起来都很不错,直到我意识到除非丢失某些东西,否则我不知道会创建哪种类型的对象.有没有办法告诉路由文件包含对象的类型?
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?
型号:
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中执行此操作的一些简单方法,我们将不胜感激任何建议!
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!
推荐答案基本上,您想在创建地址之前设置人员对象.您可以在地址控制器中执行以下操作:
Basically you want to set the person object before creating a address. You can do this in your address controller like this:
在您的地址控制器中:
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(请注意,我已经对嵌套资源使用了单数路由.您可以在此处阅读更多信息: guides.rubyonrails/routing.html#singular-resources )
(Notice that I have used singular routing for nested resource. You can read more on it here : guides.rubyonrails/routing.html#singular-resources)
更多推荐
多态控制器和调用对象
发布评论