ruby-on-rails-3 - 导轨 3 : Find parent of polymorphic model in controller?

标签 ruby-on-rails-3 polymorphic-associations

我试图找到一种优雅(标准)的方式将多态模型的父级传递给 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_idproduct_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/

相关文章:

ruby-on-rails - 使用 Rails 3 的 PayPal 自适应支付

ruby-on-rails - 多表继承上的 has_one 和多态关联

ruby-on-rails - ActiveRecord::EagerLoadPolymorphicError: 无法立即加载多态关联

ruby - Rails 4 - STI has_many :through with polymorphic association

ruby-on-rails-3 - 模型实例方法中的rails 3验证

javascript - 插入 div 时运行脚本

ruby-on-rails - Rails has_many, build, inverse_of

ruby-on-rails - 在操作之前添加浅嵌套关联 Controller

ruby-on-rails - 同一对象上的多个多态关联

polymorphic-associations - Rails 3、多态关联和无路由匹配