简体   繁体   中英

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. 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.

One of your let! statements fabricates an email which belongs to main_user, so you get, correctly one result.

UPDATE

The above is incorrect. Try 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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