ActiveRecord消息的正确关系

时间:2014-02-16 20:08:16

标签: ruby-on-rails activerecord orm

我想学习如何在ActiveRecord中正确配置和使用关系。

我有模特:

class Message < ActiveRecord::Base
  has_and_belongs_to_many :users, :association_foreign_key => :from_user_id
end

class User < ActiveRecord::Base
  has_many :messages, :foreign_key => :to_user_id
end

表格如下:

|----------------------------------------------------------------|
| id | from_user_id | to_user_id | content | created_at | status |
|----------------------------------------------------------------|
| 1  | 1            | 2          | Hi, 2!  | <...>      | red    |
| 2  | 2            | 1          | Hey, 1  | <...>      | red    |
| 3  | 1            | 2          | Whats up| <...>      | sent   |
| ...                                                            |
|----------------------------------------------------------------|

我想如何使用它:

控制器:

class MessageController < ApplicationController
  def list
    @inbox = Message.where(:to_user_id => current_user.id).order(:created_at => :desc).group(:from_user_id)
    @outbox = Message.where(:from_user_id => current_user.id).order(:created_at => :desc).group(:to_user_id)
  end
end

查看用法(由于模型未正确连接而导致失败):

<% @inbox.each do |i| %>
    <p><a href="/messages/<%=i.id%>"><%= User.find(i.from_user_id).email %></a><%= i.created_at %> <%= i.status %></p>
<% end %>

我想从i获取用户详细信息。它甚至可能吗? :)让我们说像i.user.email

从用户对象访问它也很酷。例如。 current_user.messages.inbox(来自gem'devise'的current_user)

1 个答案:

答案 0 :(得分:0)

应用/模型/ user.rb

class User < ActiveRecord::Base
  has_many :inbox_messages, foreign_key: :to_user_id, class_name: 'Message'
  has_many :outbox_messages, foreign_key: :from_user_id, class_name: 'Message'
end

应用/模型/ message.rb

class Message < ActiveRecord::Base
  belongs_to :from_user, foreign_key: :from_user_id, class_name: 'User'
  belongs_to :to_user, foreign_key: :to_user_id, class_name: 'User'
end

现在使用view你可以做(​​假设{strong>设计{/ 1}}

current_user