如何使用Ransack(使用Statesman状态的下拉菜单)从我的收藏中返回数据子集?
实施例
这是我的下拉列表;
<select class="select" name="q[state_machine_current_state_eq]" id="q_state_machine_current_state_eq">
<option selected="selected" value="pending">pending</option>
<option value="active">active</option>
</select>
记录可以是&#34;待定&#34;或者&#34;活跃&#34;。
这是我的控制器索引方法;
def index
@filter = current_sponsor
.card_holders
.ransack(params[:q])
@sponsor_card_holders = @filter
.result
.page(params[:page])
.per(3)
.decorate
end
如果我现在binding.pry
@filter
,我可以Ransack::Search<class: User::CardHolder, base: Grouping <combinator: and>>
;
@sponsor_card_holders.first.current_state
"active"
params[:q]
<ActionController::Parameters {"state_machine_current_state_eq"=>"active"} permitted: false>
state_machine_current_state_eq
我认为我的问题几乎肯定是我的下拉列表中的current_state_eq
部分。我基本上做了一个有根据的猜测。我也试过Ransack::Search<class: User::CaseWorker, base: Grouping <conditions: [Condition <attributes: ["card_holder_state_machine"], predicate: eq, values: ["active"]>]>
。
我希望它能返回类似的内容;
s
XXXX
XX X
XXX
Xe X
但它无视下拉列表。什么是正确的语法?
答案 0 :(得分:0)
事实证明,这比我预期的要复杂一些。我希望我只需要将state_machine_current_state_eq
活动更改为其他内容,这样就可以了。
实际上,你必须创建一个自定义的Ransackable Scope;
应用/模型/用户/ card_holder.rb 强>
scope :current_state, -> (state) do
# because "pending" won't exist in the database as it's the default state
if state == 'pending'
left_outer_joins(:transitions).where(card_holder_transitions: {to_state: nil})
# else return all the requested "states" (but only the most recent)
# most_recent: true is very important here for obvious reasons
else
joins(:transitions).where(card_holder_transitions: {most_recent: true}).where(card_holder_transitions: {to_state: state})
end
end
def self.ransackable_scopes(auth_object = nil)
%i(
current_state
)
end
然后你可以在你的Ransack下拉列表中调用:current_state
。
我希望有一天能帮到某人!