【发布时间】:2011-09-06 21:18:35
【问题描述】:
我正在尝试找到一种优雅(标准)的方式来将多态模型的父级传递给视图。例如:
class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end
class Employee < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
class Product < ActiveRecord::Base
has_many :pictures, :as => :imageable
end
以下方式 (find_imageable) 有效,但似乎“hackish”。
#PictureController(更新为包含完整列表)
class PictureController < ApplicationController
#/employees/:id/picture/new
#/products/:id/picture/new
def new
@picture = imageable.pictures.new
respond_with [imageable, @picture]
end
private
def imageable
@imageable ||= find_imageable
end
def find_imageable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
有没有更好的办法?
编辑
我正在执行new 操作。路径采用parent_model/:id/picture/new 的形式,参数包括父ID(employee_id 或product_id)。
【问题讨论】:
标签: ruby-on-rails-3 polymorphic-associations