我对 Rails 很陌生,并试图让三个模型与 has_many through 关系、连接模型上的备用类名以及用于将记录添加到连接模型的 collection_select 表单一起工作。三个模型如下。我对所有关联都有“accepts_nested_attributes_for”。
用户模型
has_many :match_opponents
has_many :home_opponents, :class_name => 'MatchOpponent', :foreign_key => 'home_opponent_id'
has_many :away_opponents, :class_name => 'MatchOpponent', :foreign_key => 'away_opponent_id'
has_many :matches, :through => :match_opponents
匹配模型
has_many :match_opponents
has_many :home_opponents, :class_name => 'MatchOpponent', :foreign_key => 'home_opponent_id'
has_many :away_opponents, :class_name => 'MatchOpponent', :foreign_key => 'away_opponent_id'
has_many :users, :through => :match_opponents
匹配对手模型
belongs_to :user, :inverse_of => :match_opponents
belongs_to :match, :inverse_of => :match_opponents
我的 Matches Controller 用于新建和创建:
def new
@match = Match.new
@match.home_opponents.build
@match.away_opponents.build
end
def create
@match = Match.create(match_params)
@home_opponents = @match.home_opponents.create!(params[:match_opponents])
@away_opponents = @match.away_opponents.create!(params[:match_opponents])
if @match.save
redirect_to @match, notice: 'Match was successfully created.'
end
end
我的表格:
= simple_form_for @match, html: { multipart: true } do |f|
= simple_fields_for :home_opponents do |ff|
= ff.collection_select :user_id, User.all, :id, :name, {}, {multiple: true}
= simple_fields_for :away_opponents do |ff|
= ff.collection_select :user_id, User.all, :id, :name, {}, {multiple: true}
每个模型的相关允许参数:
def match_params
params.require(:match).permit(Match::MATCH_ATTRIBUTES)
end
MATCH_ATTRIBUTES = [:match_opponent_ids => [], :user_ids => [], match_opponents_attributes: MatchOpponent::MATCH_OPPONENT_ATTRIBUTES]
def user_params
params.require(:user).permit(User::USER_ATTRIBUTES)
end
USER_ATTRIBUTES = [:match_opponent_ids => [], :match_ids => [], :match_opponents_attributes: MatchOpponent::MATCH_OPPONENT_ATTRIBUTES]
def match_opponent_params
params.require(:match_opponent).permit(MatchOpponent::MATCH_OPPONENT_ATTRIBUTES)
end
MATCH_OPPONENT_ATTRIBUTES = [:id, :home_opponent_id, :away_opponent_id, :match_id, :user_id]
我尝试了很多不同的模型配置,但无法在连接模型(MatchOpponent)上获取多条记录来保存 match_id 和 user_id 记录。
提前感谢您的帮助!