我怎样才能坚持HABTM关系?

时间:2016-03-11 18:13:00

标签: ruby-on-rails has-and-belongs-to-many

我正在使用HABTM关系进行聊天。 基本上,用户有很多聊天,聊天有很多用户。这是聊天:

class Chat < ActiveRecord::Base

  has_and_belongs_to_many :users
  has_many :messages, dependent: :destroy

end

这是用户

class User < ActiveRecord::Base

  has_and_belongs_to_many :chats
  ...

我得到了我的桌子,几个用户和几个聊天

在Rails控制台中,我尝试了

User.find(1).chats << Chat.find(1)

但是当我输入User.find(1).chats时,我得到了一个[] 我也试过

user = User.find(1)

user.chats << Chat.find(1)

user.save

也没用。我错过了什么?

以下是HABTM的迁移

class CreateChatsUsers < ActiveRecord::Migration
  def change
    create_table :chats_users do |t|
      t.belongs_to :chat, index: true
      t.belongs_to :user, index: true
    end
  end
end

编辑 - 使用has_many, through:关系

聊天:

class Chat < ActiveRecord::Base

 has_many :messages, dependent: :destroy
 has_many :users, through: :messages

end

用户:

class User < ActiveRecord::Base

  has_many :messages, dependent: :destroy

  has_many :chats, through: :messages
....

消息:

class Message < ActiveRecord::Base
  belongs_to :chat
  belongs_to :user
end

最后,迁移:

class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|
      t.belongs_to :chat, index: true
      t.belongs_to :user, index: true
      t.datetime :message_date
      t.timestamps null: false
    end
  end
end

我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

我相信如果您在迁移过程中没有id: false,RoR将不允许HABTM工作。见下文:

class CreateChatsUsers < ActiveRecord::Migration
  def change
    create_table :chats_users, id: false do |t|
      t.belongs_to :chat, index: true
      t.belongs_to :user, index: true
    end
  end
end

如果您只是在尝试本地开发环境,则只需更改迁移,然后rake db:drop db:create db:migrate即可。这将删除数据库,并运行所有迁移。永远不要在生产中完成!

如果没有,您可以生成新的迁移rails g migration remove_id_from_chats_users id:primary_key以删除id列,然后运行rake db:migrate

答案 1 :(得分:0)

好的,所以我终于找到了我的错误。

首先,是的,使用HMT关系会更好。您可以使用我在上次编辑中发布的那个。

你所要做的就是确保你有一个用户,一个聊天,以及一个链接他们的消息(这是我错过的那个)