如何称呼“主人” Rails3 中的这种多态模型

发布于 2024-10-13 02:57:15 字数 968 浏览 6 评论 0原文

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: 中创建 Building:

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

但我想问,Rail 还有其他方法可以做到这一点吗?也许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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瑾夏年华 2024-10-20 02:57:15

在那里你还必须创建额外的函数,但你不必在参数列表上创建 ifs: http ://railscasts.com/episodes/154-polymorphic-association

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文