我认为您的模型不正确(或者我不理解您的用例)。您的 RelatedGame 模型有一个 game_id 和一个名称。这个名字代表什么?如果此名称是 game_id 的名称,则不需要(您通过链接 game_id 获得名称)。如果它是另一个游戏的名称,你真的应该有另一个game_id。
我相信你的模型应该是:
模型相似度(或其他名称,这是您的相关游戏,有一些变化)
class Similarity < ApplicationRecord
belongs_to :game1, :foreign_key => 'game1_id', :class_name => "Game"
belongs_to :game2, :foreign_key => 'game2_id', :class_name => "Game"
end
模型游戏
class Game < ApplicationRecord
has_many :similarities1, :class_name => "Similarity", :foreign_key => "game1_id"
has_many :similarities2, :class_name => "Similarity", :foreign_key => "game2_id"
has_many :similar_games, :through => :similarities1, source: "Game"
has_many :inverse_similar_games, :through => :similarities2, source: "Game"
def all_similar_games
(similar_games + inverse_similar_games).uniq
end
end
游戏控制器
def edit
# The game to edit
@game = Game.find_by(id: params[:id])
# The relation table (similarity) where this game is the game1
@related = @game.similarities1
# The games related to this game (all games linked by game2 in the similarities relation, where this game is game1)
@similar_games = @game.similar_games
# All games related to this one through similarity, whether through game1 or game2
@all_similar_games = @game.all_similar_games
end
在视图中:
<h1>@game.name</h1>
<% form_for @game do |f| %>
<%= f.input_field :name %>
<%= f.collection_check_boxes :similar_game_ids, Game.all, :id, :name) %>
<% end %>