2012-06-10 17 views
4

我有一個用戶和一個角色模型,兩者都通過habtm關聯,並且有一個與角色關聯的論壇模型。在針對論壇的搜索表單中,我希望由具有特定角色的用戶(按名稱:主持人)進行過濾。如何在ransack上設置字段名的默認條件?

來源是這樣的:

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 = =:主持人)?

更新

它seesm像我必須使用自定義的ransacker,我想出了以下內容:

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查詢和查詢每個用戶。

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) 

參見::是否可以這樣像這樣結合起來,並設置SQL查詢的東西https://github.com/ernie/ransack/issues/103

回答

0

我不是100%肯定,我得到了這個問題,這是一個有點老了,但無論如何,我會嘗試:

所以,你有模型,你想搜索,你有條件,你總是想申請。現在,進入我腦海的第一件事,就是你在控制器上的結果,其中的條件,像這樣:

@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" }) %> 

如果你的意思是別的,但仍然需要這個答案,請向我解釋你的意思。我有相當的一些經驗與快速搜索,並希望提供幫助。

相關問題