【问题标题】:Rails ransack search other modelsRails ransack 搜索其他模型
【发布时间】:2017-12-06 19:48:14
【问题描述】:

我正在尝试将 Ransack 与以下示例一起使用:

用户模型

has_many :books
has_one :profile

个人资料模型

belongs_to :user

图书模型

belongs_to :user

用户的个人资料有一个名为name 的字段。在books/index.html.erb 中,有一个表有一个用户name 列:

books/index.html.erb

<td><%= book.user.profile.name %></td>

如何通过用户个人资料的名称搜索图书?

【问题讨论】:

  • 您可以先搜索 Profile 模型,然后再搜索对象,然后您可以找到它的相应书籍,例如 profile = Profile.search 然后 books =[] ; profile.map{|obj|书籍
  • @TusharPal 感谢您的回复。你能用 Markdown 格式写成答案吗?所以当我检查它时我会接受。
  • 谢谢我已经完成了

标签: ruby-on-rails ransack


【解决方案1】:

我之前也有同样的问题,我的理解ransack只能搜索直接关系,不能使用Has Many Through,现在我将ransack搜索与joins命令合并,

下面的案例是 profile.rb 的示例代码

scope :joins_user, lambda { |profile_name|
  joins(user: :book).select('profiles.*','users.*','books.*').
  where("profiles.name = ? ", profile_name)
}

以下是控制器中的示例,用于将洗劫搜索与“手动搜索”合并

@search =  Profile.all.join_user(params[:profile_name]).search(params[:q])
  • Profile.all = 返回所有配置文件
  • join_user(params[:profile_name] 将仅根据 params[:profile_name] 过滤配置文件
  • search(params[:q]) 如果您有多个过滤器,这将合并额外的 ransack 搜索,如果您只有一个过滤器,则可以将其删除

【讨论】:

    【解决方案2】:

    先在个人资料模型上搜索,然后再搜索对象时,您可以找到它的相应书籍,例如

    profile = Profile.search 
    @books =[]
    profile.map{|obj| @books << obj.books}
    

    以上是您可以实现它的方式。

    【讨论】:

    • index 操作中,有@books = Book.all。如何将books = [] 更改为@books。谢谢。
    • 编辑更改
    猜你喜欢
    • 2015-02-15
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多