私はこのような3つのモデルを持っています:
class User < ActiveRecord::Base
has_many :items
has_many :other_itmes
end
class Item < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :other_items
validate :validate_other_item_ownership
def validate_other_item_ownership
if
(user_ids = OtherItem.where(id: other_item_ids).pluck(:user_id).uniq).present? &&
(user_ids.size > 1 || user_ids.first != user_id)
then
errors.add(:other_item_ids, 'Other Items must belong to same user as Item')
end
end
end
class OtherItem < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :items
validate :validate_item_ownership
def validate_item_ownership
if
(user_ids = Item.where(id: item_ids).pluck(:user_id).uniq).present? &&
(user_ids.size > 1 || user_ids.first != user_id)
then
errors.add(:item_ids, 'Items must belong to same user as Other Item')
end
end
end
そして、次のような 2 つのコントローラー:
class ItemsController < ApplicationController
def update
@item = Item.find params[:id]
@item.other_item_ids = params[:item][:other_item_ids] #assignline
@item.save!
end
end
class OtherItemsController < ApplicationController
def update
@other_item = OtherItem.find params[:id]
@other_item.item_ids = params[:other_item][:item_ids] #assignline
@other_item.save!
end
end
現在の問題は、関連付けを正しく発生させる#assignline
呼び出しがまだ永続化されている間に、ActiveRecord が既に項目を に保存していることです。#save!
ActiveRecord::RecordInvalid
私は、ユーザーが自分が所有しているアイテムにのみリンクできるようにしたいと考えています。