Rails属性别名

时间:2010-05-15 13:49:44

标签: ruby-on-rails activerecord

我只是想知道是否可以在Rails中“重命名”一个关联。我们假设:

# An ActiveRecord Class named SomeModelASubModel (some_model_a_sub_model.rb)
class SomeModelASubModel < ActiveRecord::Base
  has_many :some_model_a_sub_model_items
end

# An ActiveRecord Class named SomeModelASubModelItem (some_model_a_sub_model_item.rb)
class SomeModelASubModelItem < ActiveRecord::Base
  belongs_to :some_model_a_sub_model
end

此时,调用some_model.items,其中some_model是SomeModelASubModel类的实例将触发未定义的方法错误。

实现这一目标的最佳做法是什么,例如: :

# With a method_alias or something, would it be possible to :
some_model = SomeModelASubModel.first # for instance
items = some_model.items

# For the reason stated, this doesn't work, one has to call :
items = some_model.some_model_a_sub_model_items

这样的速记有可能吗?

提前谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用:items代替:some_model_a_sub_model_items作为关系名称来实现此目的,并使用:class_name参数显式指定您所引用的类的名称:

# An ActiveRecord Class named SomeModelASubModel (some_model_a_sub_model.rb)
class SomeModelASubModel < ActiveRecord::Base
  has_many :items, :class_name => "SomeModelASubModelItems"
end

有关详细信息,请参阅ActiveRecord docs