我正在尝试找到一种优雅(标准)的方法来将多态模型的父级传递给视图。例如:
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
)。
Picture.all
和Picture.includes(:imageable).all
有什么区别? - Navparams[:parent_model]
字段,因为你毕竟是从父级过来的。顺便说一句,我在链接(employee**s**/:id/
)中搞砸了; 修改你的代码为...include p.pluralize}
。感谢您的帮助。我想我会在Rails Google组中发布这个问题。 - Nav