簡體   English   中英

如何在Rails3中稱呼此多態模型的“所有者”

[英]How to call “owner” of this polymorphic model in Rails3

class Chair < ActiveRecord::Base
  has_many :buildings, :as => :faculty
end

class Department < ActiveRecord::Base
  has_many :buildings, :as => :faculty
end

class Building < ActiveRecord::Base
  belongs_to :faculty, :polymorphic => true
end

在路由文件中,我有:

resources :departments do
  resources :buildings do
end

resources :chairs do
  resources :buildings do
end

如何以一種好的方式在部門和主席的一個控制器中構建新的建築物。 我知道,我可以創建另一個有用的功能,它將檢查誰創建建築物:

class BuildingsController < ApplicationController
  def new
    @parent = faculty
    @building = @parent.buildings.build
  end
end

在application_controller中:

def faculty
  if params[:department_id]
    Department.find(params[:department_id])
  elsif params[:chair_id]
    Chair.find(params[:chair_id])
  end
end

但是我問,還有其他的Rail方式嗎? 也許Rails3中存在一些我可以用來獲取信息的方法:誰想要創建建築物,而無需實現其他職能人員。

在那里,您還必須提供其他功能,但不必在參數列表上進行ifs: http : //railscasts.com/episodes/154-polymorphic-association

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM