gpt4 book ai didi

ruby-on-rails - 如何在ransack上设置带有字段名称的默认条件?

转载 作者:行者123 更新时间:2023-12-01 06:40:27 25 4
gpt4 key购买 nike

我有一个用户和一个角色模型,两者都通过 habtm 关联,并且有一个与角色关联的论坛模型。在论坛的搜查搜索表单中,我想按具有特定角色的用户(按名称:主持人)进行过滤。

源看起来像这样:

class User < ActiveRecord::Base
has_and_belongs_to_many :roles, :join_table => :users_roles
rolify

class Role < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => :users_roles
belongs_to :resource, :polymorphic => true

class Forum < ActiveRecord::Base
has_many :roles, :as => :resource
...

<%= simple_form_for @forums, :html => { :class => 'form-horizontal' } do |f| %>
...
<%= f.input :roles_users_id_in,
:collection => User.joins(:roles)
.where(:roles => {:name => :moderator}) %>

是否可以将其组合到字段名称中,我是否需要使用自定义 preciated 设置某些内容,或者如何使用预设条件进行搜索(role.name == :moderator)?

更新

看起来我必须使用自定义的掠夺者,我想出了以下内容:
class Forum < ActiveRecord::Base
..
ransacker :moderator_users, :formatter => proc { |v|
Role.joins(:users).where(:roles => { :name => :moderator,
:resource_type => :forum},
:users => {:id => v}).map(&:resource_id)
} do |parent|
parent.table[:id]
end

<%= search_form_for @q, :builder => SimpleForm::FormBuilder do |f| %>

<%= f.input :moderator_users_in,
:collection => User.joins(:roles)
.where(:roles => {:name => :moderator}),
...

使用上面的解决方法,有一个论坛 sql 查询和每个用户的查询。是否可以将其结合起来并将 sql 查询设置为这样的:
SELECT DISTINCT `forums`.* FROM `forums` 
LEFT OUTER JOIN `roles` ON `roles`.`resource_id` = `forums`.`id` AND
`roles`.`resource_type` = 'Forum'
LEFT OUTER JOIN `users_roles` ON `users_roles`.`role_id` = `roles`.`id`
LEFT OUTER JOIN `users` ON `users`.`id` = `users_roles`.`user_id`
WHERE `roles`.`name` = 'responsible' AND `users`.`id` IN (1,3,6)

另见: https://github.com/ernie/ransack/issues/103

最佳答案

我不是 100% 确定我得到这个问题而且它有点老了,但无论如何我都会尝试:

因此,您拥有想要搜索的模型,并且拥有始终想要应用的条件。现在,我想到的第一件事就是 Controller 中结果的 where 条件,如下所示:

@q = Forum(params[:q])
@forums = @q.result.where("role_id = ?", 1) # the number of course should be the id of the moderator object

或者您可以在搜索表单中尝试隐藏字段:
<%= f.select(:role_name_matches, Role.pluck(:name), :as => :hidden, :input_html => { :value => "moderator" } ) %>

如果你的意思是别的,但仍然需要回答这个问题,请向我解释你的意思。我有相当多的洗劫经验,并愿意提供帮助。

关于ruby-on-rails - 如何在ransack上设置带有字段名称的默认条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10969678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com