Ruby:如何通过Item类获取对应关联的ItemType类的name属性值
解决方案
Rails ActiveRecord 场景(绝大多数Ruby Web开发默认场景)
- 首先按照Rails命名规范调整类名和关联声明(Rails默认模型类使用单数命名,外键使用
关联名_id格式):
# ItemType 类定义 class ItemType < ApplicationRecord has_many :items end # Item 类定义 class Item < ApplicationRecord # 外键默认就是item_type_id,也就是你提到的存储关联ItemType的整数字段 belongs_to :item_type end
- 配置完成后直接调用关联属性获取name即可:
item = Item.find(1) # 直接获取关联ItemType的name值 item.item_type.name
安全调用优化:如果存在没有关联ItemType的Item实例,直接调用
name会抛出空指针错误,推荐使用安全调用符避免报错:item.item_type&.name
纯 Ruby 非框架场景
如果是自主实现的纯Ruby类,没有使用ActiveRecord,可以手动实现关联查询方法:
class ItemType attr_accessor :id, :name # 存储所有ItemType实例 @@all_records = [] def initialize(name) @name = name @id = @@all_records.size + 1 @@all_records << self end def self.all @@all_records end end class Item attr_accessor :item_type_id def initialize(item_type_id) @item_type_id = item_type_id end # 自定义方法获取关联的ItemType的name def item_type_name target_type = ItemType.all.find { |type| type.id == item_type_id } target_type&.name end end
- 调用示例:
# 初始化测试数据 electronic_type = ItemType.new("电子产品") book_type = ItemType.new("图书") item = Item.new(electronic_type.id) puts item.item_type_name # 输出:电子产品
内容的提问来源于stack exchange,提问作者Julian Wakefield
相关产品推荐
相关产品推荐

