How can I search through a has_many association in Rails 3 (meta_where or railslogic?)

1.8k Views Asked by At

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
2

There are 2 best solutions below

0
On

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})
7
On

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.