У меня есть следующие M2M через ассоциации для этих 3 моделей
Customer -> Residences <- Properties
Также модель свойства связана с адресом:
class Address < ApplicationRecord
has_one :property
end
Клиент всегда будет существовать до создания свойства.Свойство создается путем отправки адреса.
Вот действие контроллера, которое работает, за исключением случая, когда рендеринг всегда возвращает 2 свойства (т. Е. В основном 2 записи о резидентности).
Однако толькоодин находится в базе данных.Я понимаю, что это связано с устаревшими объектами , но не могу понять, как его решить.
Я пытался добавить @customer.reload
и @customer.reload.residences
и @customer.reload.properties
, но все равно получаю 2 записи.
# POST /customers/:id/properties
def create
@customer = set_customer
Customer.transaction do
address = Address.find_by_place_id(address_params[:place_id])
if address.nil?
@property = @customer.properties.create
@property.address = Address.new(address_params)
if @property.save
@customer.reload
render json: @customer, status: :created
else
render json: @property.errors, status: :unprocessable_entity
end
else
# irrelevant code to the problem
end
end
end
def set_customer
Customer.find(params[:customer_id])
end
Комментарий к этому вопросу (из @Swaps) указывает, что использование << вместо создания может иногда приводить к дублированию, но каким бы способом я это не делал, я всегда получаю 2. </p>
РЕДАКТИРОВАТЬ
Мне удалось заставить его работать так, но это похоже на взлом:
if @property.save
@customer = set_customer
render json: @customer, status: :created
else
** ОБНОВЛЕНИЕ - модели **
class Customer < ApplicationRecord
has_many :residences
has_many :properties, through: :residences
end
class Residence < ApplicationRecord
belongs_to :customer
belongs_to :property
end
class Property < ApplicationRecord
belongs_to :address
has_many :residences
has_many :customers, through: :residences
end
class Address < ApplicationRecord
has_one :property
has_one :location # ignore this, not relevant
end