我试图找到一种优雅(标准)的方式将多态模型的父级传递给 View 。例如:
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
)。
最佳答案
我不确定您要做什么,但如果您要查找“拥有”图片的对象,您应该能够使用 imageable_type 字段来获取类名。你甚至不需要一个辅助方法,只是
def show
@picture = Picture.find(params[:id])
@parent = @picture.imagable
#=> so on and so forth
end
更新
对于索引操作,您可以执行
def index
@pictures = Picture.includes(:imagable).all
end
这将为您实例化所有“可想像”。
更新二:保利之怒
对于您的新方法,您可以将 id 传递给您的构造函数,但是如果您想实例化父级,您可以从 url 中获取它,例如
def parent
@parent ||= %w(employee product).find {|p| request.path.split('/').include? p }
end
def parent_class
parent.classify.constantize
end
def imageable
@imageable ||= parent_class.find(params["#{parent}_id"])
end
您当然可以在 Controller 中定义一个包含可能的父项的常量,并使用它而不是在方法中明确列出它们。使用请求路径对象对我来说更像是“Rails-y”。
关于ruby-on-rails-3 - 导轨 3 : Find parent of polymorphic model in controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7326298/