我有这个模型关系
class User < ActiveRecord::Base
has_many :trip_memberships, dependent: :destroy
has_many :trips, through: :trip_memberships, uniq: true
end
class Trip < ActiveRecord::Base
has_many :trip_memberships, dependent: :destroy
has_many :members, through: :trip_memberships, source: :user, uniq: true
end
class TripMembership < ActiveRecord::Base
belongs_to :trip
belongs_to :user
end
当我将一些用户添加为旅行成员时,例如以下代码:
trip = Trip.last
john = User.last
trip.members # => [] Empty right now
trip.members << john
trip.members # => [john] Contains John
trip.members << john
trip.members # => [john] Contains only John, but...
TripMembership.all # => [TripMembership(trip, john), TripMembership(trip, john)]
# There is 2 memberships, even the accessor methods only show one
# member because of the :uniq option
我不想在trip_memberships
表格中有重复,但我想遵循“告诉,不要问”的原则。我不想检查给定记录是否存在。
我将此验证添加到 TripMembership 模型中
class TripMembership < ActiveRecord::Base
belongs_to :trip
belongs_to :user
validates_presence_of :trip_id, :user_id
validates_uniqueness_of :trip_id, scope: [:user_id]
validates_uniqueness_of :user_id, scope: [:trip_id]
end
当我尝试添加无法保存的记录时,我希望<<
or方法返回 false ,就像在有很多关系中一样,但似乎关系不是那样工作的。concat
through
trip.members << john # => ActiveRecord::RecordInvalid: Validation failed: Trip has already been taken, User has already been taken
任何人都知道一种优雅的归档方式吗?我认为应该这样使用api。
if @trip.members << new_member
flash[:success] = "new member added"
else
flash[:error] = "can't add this member to trip"
end