Вопрос

I've two models:

class User < ActiveRecord::Base
  before_create :add_address
  has_one :address


  def add_address
    self.address_id ||= Address.generate_new.id
  end
end

And

class Address < ActiveRecord::Base
  belongs_to :user

  def self.generate_new
    new_address = # some code generating UUID

    Address.create!({address: new_address})
  end
end

when I create User.new it creates address association, saves it, and I can fetch it with user.address and in mysql Address row has correct user_id, but User in mysql has address_id = nil. What I'm doing wrong? I've tried User.new\user.build_address both ways it creates and saves address but user always has address_id = nil

Это было полезно?

Решение

This is the way it is supposed to be. From the Rails Doc

The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association)

This means that since your Address model declares the belongs_to, that is where the foreign key should be placed.

What rails does behind the scenes when you search for user.address is does a search for the Address that has a user_id equal to the current user's id.

Something like:

Select * From addresses where user_id = <current_user>.id

Другие советы

Why do you have address_id column in user model? It should be enough for the association to have user_id on the address table.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top