Rails has_one association, access to related models

I am currently experimenting with Rails model associations to deal better with them. Currently, I have achieved what I wanted, which has a relationship table that connects the data of my two models together. The problem I am facing is that I have the feeling that there may be a better way to relate the tables to the ones I have. To give a better explanation with the code I currently have:

I have an Institution model that basically allows me to add the names of organizations (I support the models as simple as possible until I find the right method for this:

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

Then I have a user (his table layout, not Devise or Sorcery, until it is correct)

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

, , , , has_one Usermock. , , , , , , , :

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:

Rails has_one

, user_m_one.institution , user_m_one.marketing.institution?

y'all.

+4
1

, . :

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,

 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.

+1

Source: https://habr.com/ru/post/1694990/


All Articles