1

ユーザーが友達リストを持っているRailsアプリを持っています。今、私はFacebookチャレンジに似たチャレンジを作成する必要があります。ユーザーはプロセス(ゲームをプレイ)を終了でき、彼は友人にチャレンジでき、友人はリクエストを受け入れるか拒否できます。受け入れられた場合は、プロセス(ゲームをプレイ)が終了した後どちらのユーザーに勝ったかを含むメッセージを両方のユーザーに送信する必要があります。

これどうやってするの?私を助けてください。

4

2 に答える 2

2

と呼ばれる新しいモデルが必要なようですChallenge。これにはいくつかの関連があるかもしれません:

class Challenge < ActiveRecord::Base
  belongs_to :sender, class_name: "User", inverse_of: :sent_challenges
  belongs_to :receiver, class_name: "User", inverse_of: :received_challenges
end

上の対応する関連付けUser

class User < ActiveRecord::Base
  # ...
  has_many :sent_challenges,
    class_name: "Challenge", foreign_key: "sender_id", inverse_of: :sender

  has_many :received_challenges,
    class_name: "Challenge", foreign_key: "receiver_id", inverse_of: :receiver
end

その後、あなたはおそらくあなたUserに挑戦を送るための方法を持っている可能性があります

def send_challenge(friend)
  sent_challenges.create(receiver: friend)
end

あなたはあなたにいくつかの行動を起こすかもしれませんChallengesController

def index
  @challenges = current_user.received_challenges
end

def create
  @challenge = current_user.send_challenge(params[:friend_id])
  # now the sender plays the game
  render :game
end

def accept
  @challenge = current_user.received_challenges.find(params[:id])
  # now the receiver plays the game
  render :game
end

def deny
  current_user.received_challenges.destroy(params[:id])
  redirect_to challenges_url
end

def complete
  # happens at the end of the game
  # work out the winner
  # send the emails
end

もちろん、対応するルートを追加してすべてを接続し、とのビューを作成する必要がありindexますgame。たぶん、あなたはcreate人々が挑戦を出すことができるように行動に向けられたあなたの友人リストにリンクを置くでしょう。

current_user.received_challenges基本的なことをするのではなく、私がすべてをどのように実行したかに注目してChallenge.find(params[:id])ください。そうすれば、IDを推測するだけで誰でもチャレンジを受け入れることができます。うわぁ!

これに取り組むにはさまざまな方法があるので、私は「おそらく」と「たぶん」をたくさん言いました。しかし、私はそれがあなたが始めるのに十分であることを願っています。そうでない場合は、Railsチュートリアルを試すことをお勧めします-MichaelHartl'sが古典的です。

于 2013-01-10T10:45:05.137 に答える
0

もうhas_many :through関係はありますか?

:sourceユーザーは友達になることもできるため、usersテーブルにを渡す必要があります。これは次のようになります。

class User < ActiveRecord::Base
 has_many :friends
 has_many :users, :source => :friend, :through => :friends
end

PS:friendsテーブルの移行を作成して実行する必要があります。

結合テーブル(友達)にさらに列を追加することが可能です。そこにを追加できますrelationship_status。あなたが最終的に持っているように:

フレンズテーブル

ID | User_id | Friend_id | relationship_status

あなたに基づいてrelationship_statusあなたはあなたの問題を解決することができます!

于 2013-01-10T10:06:12.197 に答える