简体   繁体   English

如何在Rails 3中搜索has_many关联(meta_where或railslogic?)

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

I have a model called UserHasMessages where: 我有一个名为UserHasMessages的模型,其中:

belongs_to :message
belongs_to :user

And User.rb model is: 而User.rb模型是:

has_many :messages, :through => :user_has_messages

I want to find Users where the associated UserHasMessages has a Message_id of @message.id 我想找到关联的UserHasMessages具有@ message.id的Message_id的用户

I tried something like this (using searchlogic) but it didn't work, and did not know where to begin with meta_where: 我尝试了类似的方法(使用searchlogic),但是它不起作用,并且不知道从meta_where开始的地方:

User.user_has_message.message_id_is(@message.id).is_sender(false).last

您不需要Searchlogic,MetaSearch或MetaWhere即可实现此目的:

User.joins(:user_has_messages).where(:user_has_messages => {:message_id => @message.id})

This should probably be a has_and_belongs_to_many relationship 这可能应该是has_and_belongs_to_many关系

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. @user.messages@message.users并在其上设置一些范围。 This seems more appropriate for what you're trying to accomplish. 这似乎更适合您要完成的任务。

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

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