私は自己参照型のモデルに多くのスルー関係を持っています。結合テーブルには、関係のソースを定義する追加の列もあります。その関係に新しいオブジェクトを追加するときは、user_id、friend_id、およびsource_idに基づいて結合テーブルで重複を避けたいと思います。
ユーザーモデル
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, :class_name => "User", :through => :friendships
end
モデルに参加
class Friendship < ActiveRecord::Base
attr_accessible :friend_id, :user_id, :source_id, :alert, :hide
# Relationships
belongs_to :user
belongs_to :friend, :class_name => "User"
has_one :source
end
私はこれができることを理解しています
unless user.friends.include?(newFriend)
user.friendships.build(:friend_id => friendUser.id, :source_id => source.id)
end
しかし、それは新しいユーザーが現在のユーザーの友達に存在するかどうかを確認するようです。結合モデルレベルをチェックし、指定されたソースIDで接続が存在しないことを確認する必要があります。
これを実現する方法はいくつかあることは知っていますが、私はRuby on Railsを初めて使用し、それを実行するための「RailsWay」を探しています。