ruby-on-rails – Rails has_one关联,访问相关模型

我目前正在尝试使用Rails模型关联来更好地掌握它们.目前我已经实现了我想要的,它有一个关系表,将我的两个模型的数据连接在一起.我面临的问题是,我有这种感觉,可能有更好的方法将表格与我现有的表格相关联.为了更好地解释我目前拥有的代码:

我有一个Institution模型,它基本上允许我添加机构名称(我保持模型尽可能简单,直到我有正确的方法来执行此操作:

class Institution < ApplicationRecord
  has_many :marketings
  has_many :usermocks , through: :marketings
end

然后我有了用户(它是一个模拟表,没有Devise或Sorcery,直到这是正确的)

class Usermock < ApplicationRecord
  #has_many :marketings
  #has_many :institutions, through: :marketings
  has_one :marketing
  has_one :institution, through: :marketing
end

最后,关系表现在我称之为营销(我试图关联在营销部门工作的个人列表,有点玩弄建立我工作的机构的模型)

class Marketing < ApplicationRecord
  belongs_to :usermock
  belongs_to :institution
end

计划是,该机构将拥有一组营销人员,每个营销人员只能属于一个机构,因此Usermock类上的has_one帮助程序.它的工作原理是,如果我添加一个机构,创建一个用户,然后将用户传递到它将工作的机构,我的问题是通过用户访问机构的数据需要通过营销表完成:

institution = Institution.create(institution_name: "Test Institution")
user_mock   = Usermock.create(user_name: "Test User 1")
institution.usermocks << user_mock # builds the relationship succesfully

上面的代码有效,如果我想在代表该机构的视图中显示属于营销部门内部的用户列表,我将使用@ institution.usermocks,它会给我我想要的没问题,我可以按需要循环并输出必要的字段.

但是当我从用户的角度来看时:

user_mock.institution # Returns nil Main problem here
user_mock.marketing.institution # returns the correct information

作为Rails的新手,为了更好地展示这种关系,我能做些什么呢? user_mock.institution返回nil这一事实在我看来就像是我的糟糕设计.我已经通过了Rails Association指南,尽管它足够高效,可以通过所需的关联向我展示,但我仍然缺少这些信息.

我也研究过:
Rails has_one :through association

Rails has_one association confusion

但是我仍然不确定这个问题的正确方法,是user_m_one.institution应该返回nil并且我被强制转到user_m_one.marketing.institution吗?

来自你们的任何指针都将非常感激.

最佳答案 希望您使用外键列设置Marketing表.迁移可能如下所示:

class CreateMarketings < ActiveRecord::Migration[5.1]
  def change
    create_table :marketings do |t|
      t.references :usermock, foreign_key: true
      t.references :institution, foreign_key: true

      t.timestamps
    end
  end
end

现在,如果您查询user_mock.institution,它将生成以下Query

 SELECT  "institutions".* FROM "institutions" INNER JOIN "marketings" ON "institutions"."id" = "marketings"."institution_id" WHERE "marketings"."usermock_id" = $1 LIMIT $2  [["usermock_id", usermock_id], ["LIMIT", 1]

它将返回与usermock模型关联的机构对象.

点赞