如何在 Rails 3 中搜索 has_many 关联(meta_where 或railslogic?)
我有一个名为 UserHasMessages 的模型,其中:
belongs_to :message
belongs_to :user
User.rb 模型是:
has_many :messages, :through => :user_has_messages
我想找到关联的 UserHasMessages 的 Message_id 为 @message.id 的用户
我尝试了类似的操作(使用 searchlogic),但它不起作用,并且做了不知道从哪里开始meta_where:
User.user_has_message.message_id_is(@message.id).is_sender(false).last
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要 searchlogic、MetaSearch 或 MetaWhere 来实现此目的:
You shouldn't need searchlogic, MetaSearch, nor MetaWhere to make this happen:
这可能应该是一个
has_and_belongs_to_many
关系您还需要第三个表:
messages_users
并且迁移将类似于
设置完成后,您可以调用
@user .messages
或@message.users
并在其上设置一些范围。这似乎更适合您想要完成的任务。This should probably be a
has_and_belongs_to_many
relationshipYou will also need a third table:
messages_users
And the migration will look something like
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.