是否有更清洁或更短的方式来显示这些has_many关系?

时间:2015-09-21 04:02:33

标签: ruby-on-rails activerecord

有没有办法清理这些# 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 关系,他们看起来很残酷。我可以把它们放在一个街区或以任何方式干掉它们吗?

.text
{
    background-color:red;
    width:100px;
    word-wrap: break-word;
}

1 个答案:

答案 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

...但我觉得你在没有太多收获的情况下会失去很多可读性。