Rails中如何获取关联数据:展示Term的word与Phrase的sentence
如何在Rails的phrases_terms索引页展示关联的Term和Phrase字段?
没问题,咱们一步步来实现这个需求:
1. 完善模型间的关联定义
首先得确保三个模型之间的关联是正确配置的——这是Rails里调用关联对象属性的核心前提,你现在的代码里没显式定义关联,先补上:
在app/models/term.rb中添加:
class Term < ApplicationRecord has_many :phrases_terms, dependent: :destroy has_many :phrases, through: :phrases_terms end
在app/models/phrase.rb中添加:
class Phrase < ApplicationRecord has_many :phrases_terms, dependent: :destroy has_many :terms, through: :phrases_terms end
在app/models/phrases_term.rb中添加:
class PhrasesTerm < ApplicationRecord belongs_to :term belongs_to :phrase end
2. 优化控制器查询,避免N+1性能问题
原来的控制器index方法直接取@term.phrases_terms,在视图循环时会每次单独查询对应的Phrase,咱们用includes预加载关联数据,提升页面加载性能:
修改phrases_terms_controller.rb的index方法:
def index # 预加载phrase关联,避免N+1查询 @phrases_terms = @term.phrases_terms.includes(:phrase) end
3. 修改视图,展示关联字段
现在就可以在index.html.erb的表格里添加Term#word和Phrase#sentence的列了。注意因为所有phrases_terms都属于当前的@term,你可以直接用@term.word(更高效),也可以写通用的phrases_term.term.word适配其他场景:
<% @phrases_terms.each do |phrases_term| %> <tr> <td><%= phrases_term.id %></td> <td><%= phrases_term.term_id %></td> <td><%= phrases_term.phrase_id %></td> <!-- 添加Term的word字段 --> <td><%= @term.word %></td> <!-- 添加Phrase的sentence字段 --> <td><%= phrases_term.phrase.sentence %></td> </tr> <% end %>
这样就完成啦!现在访问http://localhost:3000/terms/1/phrases_terms就能看到对应的word和sentence字段了。
内容的提问来源于stack exchange,提问作者Dutavi
相关产品推荐
相关产品推荐

