首页 > 解决方案 > Ruby on Rails / Ransack:过滤属于当前用户的所有对象

问题描述

假设我有一个要使用 Ransack 过滤的帖子列表。我的视图模板看起来像这样(我使用 simple_form):

帖子.haml:

= search_form_for @q, class: "form" do |f|
  # this works if enabled but sure enough fails if disabled
  # = f.input :user_id_eq, as: :boolean, value: current_user.id, label: "Show only my posts"
  = f.input :title_cont, required: false
  %button{type: "submit"} Search

用户.rb

class User < ApplicationRecord
  has_many :posts
end

post.rb

class Post < ApplicationRecord
  belongs_to :user
end

[编辑:添加模型和半工作解决方案]

现在我想添加一个复选框来过滤当前用户的帖子,如下所示:[ ] Show only my posts.
我有一个关联:用户 has_many posts / post belongs_to user

如何在我的搜查表单中添加一个复选框以过滤与当前用户关联的所有帖子?

标签: ruby-on-railsransack

解决方案


推荐阅读