模型有可能屬於__,兩個模型並且有嵌套關係嗎?可以模型「belongs_to」兩個其他模型,並有嵌套關係?
什麼,我想
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個嵌套關係?如果預約也屬於培訓師以及客戶,我將不得不改變我的創作方法?
感謝
+ 1輝煌的答案!謝謝。只是一個問題,如果我從客戶頁面/視圖創建約會。我如何將教練ID添加到約會中?我是否可以在視圖中加載所有培訓師並允許用戶從下拉菜單中選擇培訓師,然後將培訓師ID分配給預約中提交的trainer_id? – 2010-08-04 09:09:26
是你對trainer_id param還是關於記錄屬性的問題? trainer_id參數由嵌套資源路由設置。 '/ trainers/123/appointmentments'將'params [:trainer_id]'設置爲123,'/ customers/123/appointmentments'設置'params [:customer_id]'爲123.約會記錄上的trainer_id屬性由has_many協會。 '@appointment = person.appointments.build'會根據什麼樣的人員類別自動將'@ appointment.trainer_id'或'@ appointment.customer_id'設置爲'person.id'(要更改默認值,那麼有:foreign_key選項屬於)。 – Zargony 2010-08-04 11:14:04
可以讓我說一下我的客戶資料,並從他的個人資料中創建約會(它會從customer_id params中獲取ID),但是如何將該約會分配給將負責該約會的培訓師。如果我有10名培訓師,我如何將約會設置爲其中一人?我想讓用戶從下拉菜單中選擇一位教練,然後將該教練的ID設置爲trainer_id字段? – 2010-08-04 21:31:44