ActiveRecord 中的松散关联

Loose associations in ActiveRecord

我是 Rails 上 Ruby 的新手,我正在尝试在 类 俱乐部、赞助商和比赛之间建立关系。

关系必须是这样的:

我的模型是这样的

class Match < ApplicationRecord
  belongs_to :team
  has_many :matchplayers
  has_many :players, through: :matchplayers
  has_many :sponsors
end

class Club < ApplicationRecord
    has_many :teams
    has_many :sponsors
    accepts_nested_attributes_for :teams, :reject_if => :all_blank, :allow_destroy => true
end

class Sponsor < ApplicationRecord
    belongs_to :club
end

我的赞助商模型迁移文件如下所示:

class CreateSponsors < ActiveRecord::Migration[5.1]
  def change
    create_table :sponsors do |t|
      t.text :name
      t.text :url
      t.text :imgUrl
      t.references :club, foreign_key: true

      t.timestamps
    end

    add_reference :matches, :sponsor, index: true
    add_foreign_key :matches, :sponsor
  end
end

我在检索每个俱乐部实例的赞助商时没有问题,但在检索与每场比赛相关的赞助商时遇到问题。

在我的 matches_controller.rb 我有这个

def show 
    @match = Match.find(params[:id])
    render :json => @match.to_json(:include => [:players, :sponsors])
end

但是当我尝试 运行 时,脚本失败了。当脚本尝试 运行 以下 SQL 语句

时出现错误消息 "no such column: sponsors.match_id"
SELECT "sponsors".* FROM "sponsors" WHERE "sponsors"."match_id" = ?

我真正希望它做的是运行下面的语句

SELECT "sponsors".* 
FROM   "sponsors" 
       LEFT JOIN "matches" 
               ON "matches"."sponsor_id" = "sponsors"."id" 
WHERE  "matches"."id" = ? 

并将结果数组放入输出 JSON 的 "sponsors" 属性中。

我一直在研究不同的 Active Record 关联类型,我觉得我完成此任务所需的关联类型比文档中描述的关联类型更宽松。

你需要 many-to-many 关系。在 rails 中有两种方法可以做到这一点。您可以阅读此 here。通常,您需要将 has_and_belongs_to_many 添加到 SponsorMatch。并创建 'join-model',其中将包含 match_id + sponsor_id。这样 ActiveRecord 将能够创建合适的 SQL 查询,因为 'join-table'.