Один удобный метод with_options
, который позволяет применять одни и те же параметры для серии вызовов методов. Вы можете использовать его следующим образом:
has_many :friendships, -> { includes :friend }
with_options through: :friendships, source: :friend do |model|
model.has_many :friends, -> { where(friendships: { status: 'accepted' }) }
model.has_many :requests, -> { where(friendships: { status: 'requested' }) }
model.has_many :requested_friendships, -> { where(friendships: { status: 'requestor' }) }
end
Я думаю, что это очень хорошо. Если вы хотите, вы можете повысить его с областью:
has_many :friendships, -> { includes :friend }
with_options through: :friendships, source: :friend do |model|
model.has_many :friends, -> { with_friendship_status 'accepted' }
model.has_many :requests, -> { with_friendship_status 'requested' }
model.has_many :requested_friendships, -> { with_friendship_status 'requestor' }
end
scope :with_friendship_status, ->(status) { where(friendships: { status: status }) }
В качестве альтернативы, вы можете сделать что-то вроде этого:
has_many :friendships, -> { includes :friend }
{ friends: "accepted",
requests: "requested",
requested_friendships: "requestor"
}.each do |assoc, status|
has_many assoc, -> { where(friendships: { status: status }) },
through: :friendships, source: :friend
end
... но я думаю, что вы потеряете много читаемости, что путь, не получив много.
Да. вы можете рассказать о дружбе и использовать их –
'-> {request}', а затем 'scope: request, {where friendshops {status:: request}}' –
Кстати, можете ли вы загрузить свою модель дружбы? его всегда приятно видеть разные идеи, так как это очень сложная вещь с множеством разных подходов. –