0

我有 2 个模型,活动和城市

class activity
  has_many :attachments, :as => :attachable 
  accepts_nested_attributes_for :attachments
  belongs_to city
end

class city
  has_many :activties
end

city_controller
  @activity_deals = @city.activities.find_all_by_deals(true)
end

查看城市

 - @activity_deals.attachments.each do |a|
    = image_tag(a.file.url, :height =>"325px", :width =>"650px" )
       = a.description

我收到错误undefined method附件'`

4

4 回答 4

1

你有课Attachement吗?您正在尝试调用附件类:- @activity_deals.attachments.each...但是您正在获取undefined method...
因此,您必须将此类添加到您的应用程序中:

class Attachment < ActiveRecord::Base
  belongs_to :activity
end

但是,我认为您正在尝试使用polymorphic

如果是这样的话:

class Attachment < ActiveRecord::Base
  belongs_to :attachable, :polymorphic => true
end

class activity
  has_many :attachments, :as => :attachable 
  accepts_nested_attributes_for :attachments
  belongs_to city
end

class city
  has_many :activties
end
于 2012-07-29T10:58:30.297 回答
1

@activity_deals将是一个Array对象Activity,而不是单个Activity对象。

我不是 HAML 用户,所以我可能会弄错语法,但你可以使用类似这样的东西:

 - @activity_deals.each do |activity|
    - activity.attachments.each do |a|
      = image_tag(a.file.url, :height =>"325px", :width =>"650px" )
         = a.description

确保查看整个错误消息,它将帮助您调试此类问题。整个消息将类似于undefined method 'attachments' for […]:Array,它告诉您您正在调用attachments的是Array,而不是Activity

于 2012-07-29T11:02:55.947 回答
1

在你的视图城市,@activity_deals是一个数组。所以上面没有“附件”定义的方法。

您必须访问数组中每个元素的附件。

像那样 :

- @activity_deals.attachments.each do |a|
= image_tag(a.file.url, :height =>"325px", :width =>"650px" )
   = a.description

- @activity_deals.each do |deal|
  - deal.attachments.each do |a|
    = image_tag(a.file.url, :height =>"325px", :width =>"650px" )
      = a.description

希望这可以帮助!

于 2012-07-29T11:15:57.950 回答
0

似乎您正在对一系列活动调用附件方法。这就是为什么它给您错误 undefined ethod attacments 的原因。请给你错误日志

于 2012-07-29T11:04:25.617 回答