簡體   English   中英

Rails洗劫和自我加入關聯查詢

[英]Rails ransack and self Join associations query

鑒於這些關聯...

class User < ActiveRecord::Base
  has_many :orders

  has_many :followers, through: :follower_follows, source: :follower
  # follower_follows "names" the Follow join table for acessing through the follower association
  has_many :follower_follows, foreign_key: :followee_id, class_name: "Follow"

  has_many :followees, through: :followee_follows, source: :followee
  # followee_follows "names" the Follow join table for accessiing through the followee association
  has_many :followee_follows, foreign_key: :follower_id, class_name: "Follow"  
end

class Order < ActiveRecord::Base
  belongs_to :user
end

...和控制器...

class OrdersController < ApplicationController
  def index
    @q = Order.ransack(params[:q])
    @orders = @q.result.includes(:user, :followers)
    # I'am not sure if the includes method is corrects
  end
end

...在我看來...

<%= search_form_for @q do |f| %>
  <%= f.label :user_id_eq %>
  <%= f.search_field :user_id_eq %>

  <%= f.submit "search" %>
<% end %>

我有這種情況:

ID = 1的用戶=>管理員角色

ID = 2的用戶=> user_id = 1的關注者

ID = 3的用戶=> user_id = 1的關注者

# select * from follows;
 id | follower_id | followee_id |         created_at         |         updated_at         
----+-------------+-------------+----------------------------+----------------------------
  1 |           2 |           1 | 2017-12-09 22:30:03.299006 | 2017-12-09 22:30:03.299006
  2 |           3 |           1 | 2017-12-09 22:30:03.304564 | 2017-12-09 22:30:03.304564

問題是:

如何設置要通過f.search_field:user_id_eq(或其他任何東西)查找的點菜,以獲取user_id = 1擁有的所有訂單商品加上user_id = 2並擁有user_id = 3的所有訂單商品?

非常感謝您的支持。

Order.ransack(user_id_eq_any: [1,2,3]).result

f.search_field :user_id_eq_any

Rails + Ransack-下拉列表集合?

如果要輸入作為選擇,請參考上面的答案,添加“ multiple”屬性以允許選擇多個

在您回答之后,我嘗試了:

Order.ransack(user_followees_id_eq: 17).result

看來這就像我想要的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM