0

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. 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. I want to get the message back via the receiving_user but not via the 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.

4

1 回答 1

0

你的一个让!statements 伪造了一封属于 main_user 的电子邮件,所以你得到了一个正确的结果。

更新

以上是不正确的。尝试if messages.any?而不是if messages因为它总是返回 true,因为关联返回一个数组(如果没有匹配的记录,则为空数组)

于 2013-10-15T11:48:06.380 回答