I have three models like this:
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
And two controllers like this:
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
The Problem now is that ActiveRecord already saves the items on #assignline
, while the call to #save!
correctly raises ActiveRecord::RecordInvalid
the association is still persisted.
I want the user only to be able to link to items to each other which he owned.