1

I have a model called UserHasMessages where:

belongs_to :message
belongs_to :user

And User.rb model is:

has_many :messages, :through => :user_has_messages

I want to find Users where the associated UserHasMessages has a Message_id of @message.id

I tried something like this (using searchlogic) but it didn't work, and did not know where to begin with meta_where:

User.user_has_message.message_id_is(@message.id).is_sender(false).last
Satchel
  • 16,414
  • 23
  • 106
  • 192

2 Answers2

2

You shouldn't need searchlogic, MetaSearch, nor MetaWhere to make this happen:

User.joins(:user_has_messages).where(:user_has_messages => {:message_id => @message.id})
Ernie
  • 896
  • 5
  • 7
1

This should probably be a has_and_belongs_to_many relationship

class User < ActiveRecord::Base

    has_and_belongs_to_many :messages

end

class Message < ActiveRecord::Base

    has_and_belongs_to_many :users

end

You will also need a third table:

messages_users

And the migration will look something like

class CreateMessagesUsers < ActiveRecord::Migration
  def self.up
    create_table :messages_users do |t|
      t.integer :user_id
      t.integer :message_id

      t.timestamps
    end
  end

  def self.down
    drop_table :messages_user
  end
end

Once that is setup, you can call

@user.messages or @message.users and setup some scopes on that. This seems more appropriate for what you're trying to accomplish.

jaredonline
  • 2,912
  • 2
  • 17
  • 24
  • Are we also doing this under the Class or an object? Wouldn't it be more like @user.messages.find_by_id...? Maybe I'm missing something. Mid-afternoon naps are death to intellect – Kyle Macey Mar 29 '11 at 01:14
  • @jaredonnline -- thanks, I have to extract them because there is both a sender and a receiver for every message, and poeple may delete or change and sof roth so I need to abstract it to have two separate associations...will this work since it is a :has_many, :through? – Satchel Mar 29 '11 at 05:07
  • It should work just fine. The :through part just tells rails to reach through another model to find the association. Try it in your console, and tell me if it works. – jaredonline Mar 29 '11 at 18:02
  • @jardeonline -- @user.messages displays an error, so I can't access messages..... – Satchel Mar 29 '11 at 21:14
  • Ah. This is because your UserHasMessages model doesn't specify a has_many relationship of its own. You know.. there's a paradigm for this, called a :has_and_belongs_to_many relationship. I think you should try that. I will update my answer to show you what things should look like. – jaredonline Mar 30 '11 at 02:18
  • @jaredonline...thank you I will try it, i think I had to change my model because it was plural and causing troubles – Satchel Apr 01 '11 at 04:14
  • hello how is has_many_and_belongs_to different from my belongs_to and has_many I am having some difficulty following to understand it thanks – Satchel Apr 01 '11 at 04:17