多态控制器和调用对象

编程入门 行业动态 更新时间:2024-10-11 13:23:14
本文介绍了多态控制器和调用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我与地址具有多态关系,地址既可以由成员也可以由属拥有.一切看起来都很不错,直到我意识到除非丢失某些东西,否则我不知道会创建哪种类型的对象.有没有办法告诉路由文件包含对象的类型?

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)

更多推荐

多态控制器和调用对象

本文发布于:2023-08-03 14:27:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1287666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   对象   多态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!