Rails:select 加入时的相关活动记录 table

Rails: select related active records on join table

我有两个模型 Magazine.rbKeyword.rb,两者通过简单的连接 table 相关。一本杂志可以定义很多关键词,一个关键词可以定义很多杂志。

class Keyword < ActiveRecord::Base
  attr_accessible :word
  has_and_belongs_to_many :magazines, :join_table => "magazines_keywords"
end

class Magazine < ActiveRecord::Base
  has_and_belongs_to_many :keywords, :join_table => "magazines_keywords" 
end

现在我想在 ingredients/show.html.erb 上显示通过杂志或几本杂志与给定关键字相关的所有关键字,这将是共享相同的所有其他关键字 magazine_id 加入 table。我的控制器操作如下:

class IngredientsController < ApplicationController
  def show
    @keyword = Keyword.find(params[:id])
    @keywords = Keyword.find(:all, :order => 'word ASC')
    @k = Keyword.count
  end

我目前认为:

Related Keywords
<% i= @k
for keyword in @keywords %>
  <a href="/ingredients/<%= keyword.id %>">
    <div class="keyword">
      <%= keyword.word %>
    </div>
  </a>
<%  i -= 1
end %>

但是我显示了所有的关键字。如何实现只获取相关条目?

更新

在同一个视图中,我可以通过以下方式显示与给定关键字相关的所有杂志:

Related Magazines
<% @keyword.magazines.each do |s| %>
  <div>
    <a href='/magazines/<%= s.id %>')>
      <div>Magazin <%= s.number %></div>
    </a>
  </div>
<% end %>

如果您只想获取相关关键字,请尝试使用以下查询:

@keywords = Keyword.joins(magazines: :keywords).where('keywords_magazines_join.keyword_id': @keyword.id).uniq.order(:word)

keywords_magazines_join 是 Rails 为 magazines_keywords table 在此 table 的第一个 INNER JOIN 之后生成的别名。