heroku上的Rails HABTM模型显示“model_id”,“name”和“timestamp”而不是简单的“name”

时间:2011-12-03 19:45:23

标签: ruby-on-rails-3 heroku has-and-belongs-to-many

这一定很简单,但我找不到办法。

我有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">] 

任何人都知道如何解决这个问题? 非常感谢!

1 个答案:

答案 0 :(得分:2)

我不确定为什么你会在本地看到name,但你在Heroku上看到的是to_strip.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 %>

这将导致:“category1,category2和category3”,或者其他一些。