简体   繁体   English

活动记录虚拟模型

[英]active record virtual model

I have a user model and an email model. 我有一个用户模型和一个电子邮件模型。 The user can create emails and receive them. 用户可以创建电子邮件并接收它们。 A received email is realy just an email, but joined to the user on different field. 收到的电子邮件实际上只是一封电子邮件,但已加入到不同领域的用户。 My setup is below, but it doesn't work correctly. 我的设置在下面,但无法正常运行。 When I call received_messages on a user that created an email (and did not receive it) he also sees a message. 当我在创建电子邮件(但未收到电子邮件)的用户上调用receive_messages时,他也会看到一条消息。 Is this possible at all this way? 这样到底有可能吗?

class User < ActiveRecord::Base
  has_many :mail_messages
  has_many :received_messages, class_name: 'MailMessage', foreign_key: 'to_id'
end

class MailMessage < ActiveRecord::Base
  belongs_to :user
emd

I did create a controller for these messages: 我确实为这些消息创建了一个控制器:

class ReceivedEmailsController < ApplicationController

  before_filter :authenticate_user!

  def index
    messages = current_user.received_messages

    if messages
      render json: messages, each_serializer: MailMessageSerializer, status: :ok
    else
      render json: :nothing, status: :not_found
    end
  end

  def show
    message = current_user.received_messages.where(id: params[:id]).first

    if message
      render json: message, serializer: MailMessageSerializer, status: :ok
    else
      render json: :nothing, status: :not_found
    end
  end
end

The tests: 测试:

  describe ReceivedEmailsController do

    let!(:main_user) { Fabricate :user }
    let!(:receiving_user) { Fabricate :user }
    let!(:message) { Fabricate :mail_message, user_id: main_user.id, to_id: receiving_user.id }

    describe 'get index' do

      it 'should give not found when there are no emails received' do
        main_user.confirm!
        sign_in main_user
        get :index
        JSON.parse(response.body)['received_emails'].size.should eq 0
      end
    end
  end

Instead of 0 I get 1 back, the same message that I get back when doing the test via the receiving_user. 我得到的不是原来的0,而是0,而是与通过receive_user进行测试时得到的相同的消息。 I want to get the message back via the receiving_user but not via the main_user. 我想通过receive_user而不是通过main_user取回消息。

I'm not sure whether it can be done this way, whether to use scopes, or even something else I'm not aware of. 我不确定是否可以通过这种方式完成操作,使用范围还是其他我不知道的内容。

Thanks. 谢谢。

One of your let! 让你之一! statements fabricates an email which belongs to main_user, so you get, correctly one result. 语句伪造了一个属于main_user的电子邮件,因此您正确地获得了一个结果。

UPDATE 更新

The above is incorrect. 以上是不正确的。 Try if messages.any? 试试看if messages.any? instead of if messages as it will always return true, since associations returns an array (empty array if there are no matching records) 而不是if messages将始终返回true,因为关联会返回一个数组(如果没有匹配的记录,则为空数组)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM