开发者

How to call "owner" of this polymorphic model in Rails3

开发者 https://www.devze.com 2023-02-05 23:45 出处:网络
class Chair < ActiveRecord::Base has_many :buildings, :as => :faculty end class Department < ActiveRecord::Base
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

In routes file I have:

resources :departments do
  resources :buildings do
end

resources :chairs do
  resources :buildings do
end

How can I build in good way a new Building in one controller for Department开发者_运维百科 and Chair. I know, that I can create another helpful function, that it will check for who create Building:

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

in application_controller:

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

but I am asking, is there any other Rail's way to do it? Maybe there exist some method in Rails3 that I can use to get information: Who want's to create building, without implementing another function faculty.


There you also have to make additional function, but you don't have to make ifs over params list: http://railscasts.com/episodes/154-polymorphic-association

0

精彩评论

暂无评论...
验证码 换一张
取 消