2012-07-29 60 views
0

我有2個車型,活動和城市Rails 3個的關係

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附件`

回答

1

@activity_dealsActivityArray對象,而不是一個單一的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,它告訴你,你打電話attachmentsArray,而不是Activity

+0

它的工作原理!謝謝.. HAML代碼爲城市x中的所有活動交易生成一個jQuery內容滑塊。我也有一個活動模型,其活動關係相同。我可以在一個查詢中組合事件和活動,並將輸出存儲在@activity_event_deals中? 非常感謝! – Remco 2012-07-29 11:27:56

+0

你是賴特...我已經找到了解決方案。 – Remco 2012-07-29 11:51:22

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 
0

看起來你正在調整一系列活動的附件方法..這就是爲什麼它給你錯誤的未定義的方法attacments。請給ü錯誤日誌

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 

希望這有助於!