2011-12-03 18 views
0

這一定很簡單,但我找不到方法。Heroku上的Rails HABTM模型顯示「model_id」,「name」和「timestamp」而不是簡單的「name」

我有2個模型與HABTM關係。

Trip.rb

has_and_belongs_to_many :categories 

Category.rb

has_and_belongs_to_many :trips 

旅行index.html.erb

<%= trip.categories %> 

一切都很好,我的本地機器上 - 我只看到該類別名稱。

但是當我部署到Heroku的,而不是類的名字,我看到

[#<Category id: 1, name: "Surfing", created_at: "2011-10-20 12:28:57", updated_at: "2011-10-20 12:28:57">] 

任何人知道如何解決這一問題? 非常感謝!

回答

2

我不知道你爲什麼會看到name地方,但你看到的在Heroku是to_s結果被隱式調用的trip.categories協會,這是類別記錄的數組。

# You could define the `to_s` of Category to return the name. 
class Category 
    def to_s 
    name 
    end 
end 

# or define a method to return a mapping of the category names: 
class Trip 
    # via an association extension 
    has_and_belongs_to_many :categories do 
    def names 
     map(&:name) 
    end 
    end 

    # or a simple instance method 
    def category_names 
    categories.map(&:name) 
    end 
end 

Trip.first.categories.names #=> [cat1, cat2] 
Trip.first.category_names #=> [cat1, cat2] 

但當前模板仍然會爲一個字符串Array落入輸出,如:

["category1", "category2", "category3"] 

你可能想更重要的是這樣的:

<%= trip.categories.map(&:name).to_sentence %> 

哪會導致:「類別1,類別2和類別3」,或者某些類型。

+0

是的,你是對的,它的工作原理。我已經定義了類別的'to_s',可能這就是爲什麼我可以在本地看到名字的原因。無論如何謝謝你! – emilsw

相關問題