1

ユーザーの「表示」ページにこれらを表示するために、ユーザーに自己参照的に関連する一連のレコードを引き出すのに本当に苦労しています。

アイデアは次のとおりです。

ユーザー ( ) は、他の 2 人のユーザー (および)current_user間の互換性を評価します。互換性を肯定的または否定的に評価できます。2 人のユーザーを「互換性がある」と評価すると、user_a と user_b の間に が作成され、「互換性がない」と評価すると. したがって、positive_connection、negative_connection、およびユーザーのモデルがあります。user_auser_bpositive_connectionnegative_connection

ここで、あるユーザーのみを表示する必要がありますoverall_positively_connected_to(@user)(つまり、 where positive_connections_to(@user).count > negative_connections_to(@user).count).

これは私がしなければならないところですが、それ以上先に進むことはできません:

ユーザーモデル:

  def overall_positive_connected_to(user)
      positive_connections_to(user).count > negative_connections_to(user).count
  end


  def positive_connections_to(user)
      positive_connections.where("user_b_id = ?", user)
  end     

  def negative_connections_to(user) 
      negative_connections.where("user_b_id = ?", user)
  end

コントローラ

@user.user_bs.each do |user_b|
  if user_b.overall_pos_connected_to(@user)
    @compatibles = user_b
  end
end

コントローラーのコードは明らかに間違っていますが、これを行うにはどうすればよいですか? 私はレール(およびSQL)にまったく慣れていないので、素朴なことをしたかもしれません。

どんな助けでも素晴らしいでしょう。

4

1 に答える 1

1

だから私はあなたが3つのモデルを持っていると言っているのは正しいですか

  • ユーザー(ID、名前)
  • PositiveConnection(user_a_id、user_b_id)
  • NegativeConnection(user_a_id、user_b_id)

またはそのようなもの。

2つのモデルが必要だと思います。便宜上、リレーションの名前を「from_user」と「to_user」に変更します。

  • ユーザー(ID、名前)
  • 接続(値:整数、from_user_id、to_user_id)

ここで、値は負の場合は-1、正の場合は+1です。

これで、次のようなことができます(注::foreign_key、:sourceなどの正確な構文を整理する必要があります)

class User

  has_many :connections, :foreign_key => "from_user_id"
  has_many :connected_users, :through => :connections, :source => :to_user

  def positive_connections
    connections.where(:value => 1)
  end

  def negative_connections
    ...
  end

end

しかし、複雑なSQLクエリを作成するためのフレームワークもあります(ここでも空白を埋める必要があります...しかし、次のようなものです)

class User

  def positive_connected_users
    connected_users.joins(:connections).group("from_user_id").having("SUM(connections.value) > 0")
  end

end

これは完全には機能しませんが、実際のソリューションの一種の擬似コードです

(純粋なSQL用語で考える方が良いかもしれません)

SELECT users.* FROM users
INNER JOIN connections ON to_user_id = users.id
WHERE  from_user_id = #{user.id}
HAVING SUM(connections.value) > 0
于 2011-06-13T20:37:24.770 に答える