与2个模型相关的控制器问题

时间:2012-03-06 14:49:11

标签: ruby-on-rails ruby-on-rails-3

我在网站上有我的图像的附件模型和控制器。

关系是(多态的):

class House
  has_many :attachments, :as => :attachable
end

class Apartment
  has_many :attachments, :as => :attachable
end

附件控制器看起来像这样存储正确的变量。

class AttachmentController
  @appartment = Appartment.find(params[:apartment_id])
  @attachments = @appartment.attachments
end

这适用于公寓页面/路径。 (公寓/ 1 /资产)但在房子页面(房子/ 1 /资产)我收到错误消息“找不到没有ID的公寓”

我该如何处理这种/最好的方法?控制器中的条件?

2 个答案:

答案 0 :(得分:0)

您需要先检查哪些键存在,如下所示:

class AttachmentController
  before_filter :prepare_attachable

  def index
    @attachments = @attachable.attachments
  end

  private

  def prepare_attachable
    if params.kas_key?(:apartment_id)
      @attachable = Apartment.where(:id => params[:apartment_id]).first
    elsif params.kas_key?(:house_id)
      @attachable = House.where(:id => params[:house_id]).first
    end
    raise ActiveRecord::RecordNotFound if @attachable.blank?
  end
end

答案 1 :(得分:0)

可能的问题......

“公寓”与公寓

相关问题