多次引用相同的模型字段

时间:2013-02-04 03:56:20

标签: ruby-on-rails-3 postgresql model associations

我有一个Lesson模型,其中包含大约50个都引用Grade模型的字段。成绩模型有一个简单的0-8列表,用作课程评分值。

有没有办法避免用50行填充我的模型:

 belongs_to :walking, :class => 'Grade'
 belongs_to :running, :class => 'Grade'   
 belongs_to :crawling, :class => 'Grade' 
 ...

postgres数据库

1 个答案:

答案 0 :(得分:0)

你可以这样做:

fields = %w[walking running crawling] # list all 50 of them here
fields.each { |field| belongs_to field.to_sym, :class => 'Grade' }

这至少可以让你不必写出所有的线路,但你仍然需要列出关联的名称(步行,跑步,爬行等)才能发挥作用(正如我上面所说的) )。

相关问题