Ruby on Rails中Path模型关联Termlist、TermlistPath出现undefined method报错求解
错误根因
- 视图中
museum_object.path.path.split("/")返回的是字符串数组,取到的second/third等结果都是字符串类型,字符串没有ActiveRecord关联方法,直接调用关联方法必然报错 - Path模型关联定义有误:原代码同时写了
has_one :termlist_path和has_many :termlists, through: :termlist_paths,单数复数不匹配,through参数无法找到对应关联
修复步骤
1. 修正Path模型关联
class Path < ApplicationRecord has_many :termlist_paths # 将原has_one改为has_many,匹配through后的复数关联名 has_many :museum_objects has_many :termlists, through: :termlist_paths end
2. Path模型新增解析方法
将path字段解析逻辑封装到模型中,避免视图层处理业务逻辑:
class Path < ApplicationRecord # 原有关联省略 # 按顺序返回path字段对应Termlist数组 def parsed_termlists segment_ids = path.split("/").reject(&:empty?).map(&:to_i) segment_ids.map do |id| termlists.find_by(id: id) end end end
3. 调整视图代码
直接调用模型封装好的方法渲染内容,使用&.安全操作符避免不存在对应Termlist时报错:
<% @museum_objects.each do |museum_object| %> <% path_termlists = museum_object.path.parsed_termlists %> <tr> <td><%= museum_object.inv_number %></td> <td><%= museum_object.storage_location.storage.name_en %></td> <td><%= museum_object.storage_location.name_en %></td> <td><%= path_termlists[0]&.name_en %></td> <td><%= path_termlists[1]&.name_en %></td> <td><%= path_termlists[2]&.name_en %></td> <td><%= path_termlists[3]&.name_en %></td> <td><%= museum_object.production_technique.termlist.name_en %></td> <td><%= museum_object.preservation_material.termlist.name_en %></td> </tr> <% end %>
可选优化
如果TermlistPath表中存储了每个路径对应术语的排序字段,可直接按排序字段读取关联的Termlist,无需解析path字符串,逻辑可靠性更高。
内容的提问来源于stack exchange,提问作者Emily
相关产品推荐
相关产品推荐

