访问最近创建的记录的ID和允许重复

时间:2014-05-09 03:20:58

标签: ruby-on-rails activerecord has-many-through

我遇到has_many through:型号的问题。

我想做的是在我的模型中创建2人聊天室。因此,用户通过聊天has_many聊天和has_many消息。

如何访问最近创建的ID并允许该ID不唯一?另外,我是否正确设置了我想要做的事情?

@u = User.find_by_id(1)
@u.chats.new.save <--How to get this chat id to associate with another user id?

我的模特:

class User < ActiveRecord::Base
    has_many :chats
    has_many :messages, through: :chats
end

class Chat < ActiveRecord::Base
    belongs_to :user
    belongs_to :message
end

class Message < ActiveRecord::Base
    has_many :chats
    has_many :users, through: :chats
end

2 个答案:

答案 0 :(得分:1)

这很难 - 我们最近使用以下设置实现了类似的东西:

#app/models/user.rb
Class User < ActiveRecord::Base
    #Chats
    def messages
        Chat.where("user_id = ? OR recipient_id = ?", id, id) # -> allows you to call @user.chats.sent to retrieve sent messages
    end
end

#app/models/chat.rb #- > id, user_id, recipient_id, message, read_at, created_at, updated_at
Class Chat < ActiveRecord::Base
    belongs_to :user
    belongs_to :recipient, class_name: "User", foreign_key: "recipient_id"

    #Read
    scope :unread,  ->(type) { where("read_at IS #{type} NULL") }
    scope :read,    ->       { unread("NOT") }

    #Sent
    scope :sent,     -> { where(user_id: id) }
    scope :received, -> { where(recipient_id: id) }
end

此设置会使每个chat&#34;拥有&#34;由特定用户。这是在您创建消息时完成的,并代表sender。每条消息都有一个recipient,您可以使用recipient_id

查看

因此,您可以向用户发送新消息,如下所示:

@chat = Chat.new(chat_params)

def chat_params
   params.require(:chat).permit(:user_id, :recipient_id, :message)
end

对于单个聊天室(两个用户之间的I.E单个消息脚本 - 私人消息等),这是可以的。


您能解释一下您的聊天室需要如何工作吗?例如,如果你只有双向聊天,你肯定可以使用我的上述代码吗?但是,我觉得它不对;因此,我想重构或者你可以容纳多个聊天室

答案 1 :(得分:0)

我确定有更好的方法可以做到这一点,但这应该可以为您提供所需的结果。

@u = User.find(1) # You can use "find" instead of "find_by_id"
(@chat = @u.chats.new).save
@chat.users << User.find(x) # However you want to get the other user in the chat
相关问题