ruby-on-rails – 可以模拟“belongs_to”两个其他模型并且具有
发布时间:2020-12-16 21:50:38 所属栏目:百科 来源:网络整理
导读:一个模型是否可以属于两个模型并具有嵌套关系? 即我想要的 class trainerhas_many :appointmentsendclass appointmentbelong_to :trainer,:customerendclass customerhas_many :appointmentsend 在这一刻,我只有客户和约会模型是嵌套的,例如我所拥有的: 创
一个模型是否可以属于两个模型并具有嵌套关系?
即我想要的 class trainer has_many :appointments end class appointment belong_to :trainer,:customer end class customer has_many :appointments end 在这一刻,我只有客户和约会模型是嵌套的,例如我所拥有的: 创建方法如下所示: def create @appointment = @customer.appointments.build(params[:appointment]) respond_to do |format| if @appointment.save format.html { redirect_to([@customer,@appointment],:notice => 'Appointment was successfully created.') } format.xml { render :xml => @appointment,:status => :created,:location => @appointment } else format.html { render :action => "new" } format.xml { render :xml => @appointment.errors,:status => :unprocessable_entity } end end end 在路线我有: map.resources :patients,:has_many => [ :appointments,:visits ] 1个模型可能有2个嵌套关系吗?如果约会也属于培训师以及客户,我该怎么改变我的创建方法? 谢谢 解决方法
假设您正在使用ActiveRecord:当然,模型属于多个其他模型是可能的(但是您需要为每个关系指定一个belongs_to语句).
class Appointment < ActiveRecord::Base belongs_to :trainer belongs_to :customer end 一个belongs_to关系不一定意味着该记录实际上具有该其他记录相关;它也可以是零.所以你可以有一个属于教练的人,但没有客户,反之亦然. 实际上,您甚至可以既没有培训者也不是客户,培训师和客户也不会这样 – 如果这违反了您的业务逻辑,您可能需要添加一个验证来防止这种情况. 您现有的控制器创建方法应该继续工作,您只需要添加培训师记录的处理.您甚至可以使用相同的控制器来通过抽象培训师和客户来处理培训师和客户的任用.成为这样的人: class AppointmentsController < ApplicationController def create @appointment = person.appointments.build(params[:appointment]) # ... end protected def person @person ||= if params[:trainer_id] Trainer.find(params[:trainer_id]) elsif params[:customer_id] Customer.find(params[:customer_id]) end end end 这样,您可以对两条路线使用相同的AppointmentsController # Use AppointmentsController for /trainers/123/appointments # as well as for /customers/123/appointments map.resources :trainers,:has_many => :appointments map.resources :customers,:has_many => :appointments 当然,如果培训师任用和顾客约会背后的逻辑和观点几乎相同,这只能是有意义的.如果没有,还可以使用不同的控制器 # Use TrainerAppointmentsController for /trainers/123/appointments and # CustomerAppointmentsController for /customers/123/appointments map.resources :trainers do |trainer| trainer.resources :appointments,:controller => 'trainer_appointments' end map.resources :customers do |customer| customer.resources :appointments,:controller => 'customer_appointments' end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |