Rails ActiveRecord通过has_many查找

Ada*_*ite 1 ruby activerecord join ruby-on-rails ruby-on-rails-3

iOS开发人员在此处学习Rails。尝试查询活动记录以基于has_many关系的属性的记录。抱歉,这很简单,但我无法弄清楚。我读过有关,并已尝试使用scope.where.joins,但有这么多矛盾的帖子和博客在网上我不确定它使用的,什么是正确的?

关于这个问题:

我有两个ActiveRecord模型:

class User < ActiveRecord::Base
  has_many :items
end
Run Code Online (Sandbox Code Playgroud)

class Item < ActiveRecord::Base
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

一个项目具有属性title,我试图找到所有User具有的项目与title类似于字符串格式的某些搜索参数的。

我设法通过搜索项目来做到.map这一点,然后像这样:

users_owning_item_in_search_parameter = Item.where{ (title =~ my{@search_param + "%"}) }.map! { |i| i.user }
Run Code Online (Sandbox Code Playgroud)

(该语法来自squeel gem。)

但是,Array当我需要时,该命令将返回一个ActiveRecord::Relation,因为我需要做一些进一步的过滤,需要这种实例类型。

任何帮助,不胜感激。

Hel*_*rra 5

我认为您正在寻找这样的东西:

User.joins(:items).where('items.title LIKE ?', "#{@search_param}%")
Run Code Online (Sandbox Code Playgroud)

如果要利用squeel,则必须对其进行一些修改。

  • 如果有人想知道,则发出Squeel:`User.joins(:items).where {items.title =〜my {param +“%”}`` (2认同)