gpt4 book ai didi

ruby-on-rails - Rails 属性别名

转载 作者:行者123 更新时间:2023-12-04 06:15:15 26 4
gpt4 key购买 nike

我只是想知道是否可以在 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

这样的简写可能吗?

提前致谢!

最佳答案

您可以通过使用 :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了解更多信息。

关于ruby-on-rails - Rails 属性别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2840341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com