2015-09-21 10 views
0

Есть ли способ убрать эти отношения has_many, они жестоки, чтобы посмотреть. Могу ли я положить их в блок или сушить их каким-либо образом?Есть ли более чистый или более короткий способ отображения этих отношений has_many?

# mymodel.rb 
has_many :friendships, -> { includes :friend } 

has_many :friends, -> { where(friendships: { status: 'accepted'}) }, 
    through: :friendships, :source => :friend 

has_many :requests, -> { where(friendships: { status: 'requested'}) }, 
    through: :friendships, :source => :friend 

has_many :requested_friendships, -> { where(friendships: { status: 'requestor'}) }, 
    through: :friendships, :source => :friend 
+0

Да. вы можете рассказать о дружбе и использовать их –

+1

'-> {request}', а затем 'scope: request, {where friendshops {status:: request}}' –

+0

Кстати, можете ли вы загрузить свою модель дружбы? его всегда приятно видеть разные идеи, так как это очень сложная вещь с множеством разных подходов. –

ответ

2

Один удобный метод 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 

... но я думаю, что вы потеряете много читаемости, что путь, не получив много.

Смежные вопросы