2014-05-09 60 views
0

我遇到与has_manythrough:模型有关的问题。访问最近创建的记录的ID并允许重复

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

如何访问最近创建的标识并允许该标识非唯一?另外,我是否有适合自己想要做的事情的设置?

@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 

回答

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“拥有”特定用户。这是在您创建消息时完成的,并代表sender。每个消息只有一个recipient,您可以用recipient_id

看到那么你就可以将新邮件发送给用户这样的:

@chat = Chat.new(chat_params) 

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

这将是好的单个聊天室(IE两个用户之间的单个消息转录 - 私人消息等)。


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

+0

Ahhh我可以'belongs_to'两次同一个班级吗?太棒了...这看起来不错。谢谢!关于我的聊天工作方式,我的目标是每个人都可以与其他人进行多对一的聊天。实际的聊天内容在移动设备上,这是我的服务器端。聊天内容可以为空,因为我可以开始与某人聊天而不实际发送任何消息。这看起来也可以做到这一点。与你实现的聊天方式有什么不同,并且它是一个has_many'消息的连接表吗? –

+0

听起来像你真的在谈论私人消息?如果您总是要将消息发送给其他用户,那么这些消息将永远处于单个对话中。我所拥有的连接表和连接表之间的差异将使您可以灵活地在每次聊天中拥有多个用户。我的设置是Facebook类型的“一对一”的消息,而一个更可扩展的系统将需要我的连接模型 –

+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