0

多対多の関係を持つ 2 つのエンティティがあります。ユーザー:

class User < ActiveRecord::Base
    has_and_belongs_to_many :conversations
end

そして会話

class Conversation < ActiveRecord::Base
     has_and_belongs_to_many :users

多数のユーザーがいますが、このユーザー間の会話を選択するにはどうすればよいですか?

現在find_by_sql、JOIN 演算子を使用した大規模な SQL クエリを使用していますが、これは良いアプローチではないと思います。

4

1 に答える 1

0

オブジェクトを作成する前にそれらを関連付けて、マイグレーションで結合テーブルを作成することを忘れないでください。

段階的に、次のようになります: まず、正しいことを行い、モデルを関連付けます ( http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association必要なものはすべてあります)。次に、次のような移行を作成します。

class CreateConversationUserJoinTable < ActiveRecord::Migration
  def change
    create_table :conversations_users, :id => false do |t|
      t.references :conversation
      t.references :user
    end
  end
end

実行rake db:migrateして準備完了です。

コントローラーでこれらのモデルを関連付ける例があります。

@user.conversations << @my_conversation

に行くと、rails console次のようなユーザーとの会話を確認できます。

$ User.find(1).conversations

私の記憶力がよければ、それだけです。

幸運を!

于 2013-06-14T07:54:18.200 に答える