按属性搜索时重定向到模型对象的"show"视图(非 ID)



我有一个表单,用户可以通过该法案的某些属性(即"国会编号","账单类型"和"账单编号"(查找特定法案,如114-H.R.-67。我想"显示"适当的账单,但要做到这一点,我已经在一个单独的操作中获得了适当的账单模型,我称之为"find_by_attributes"。在此操作中,我执行:

@bill = Bill.find_by( params ).first

正确获取相应账单的 ID。

现在我只想重定向到该法案的"显示"方法,如 url 中

".../bills/[@bill.id]"

截至目前,在我的"find_by_attributes"操作结束时,我做了

redirect_to bills_path(@bill)

它正确地加载了带有@bill的 show.html.erb,但不会更改 URL(URL 仍然显示"find_by_attributes"操作,后跟一个长查询字符串,而不是干净的"/bills/[:bill_id]"。

如何重组代码以实现我想要的整洁重定向?

完整代码如下:

表格

<%= form_tag("bills/find_or_create", :method => :get ) do |f| %>
<%# render 'shared/error_messages', object: f.object %>
<%= fields_for :bill do |ff| %>
<%= ff.label :congress, 'Congress (i.e. 114)' %>
<%= ff.number_field :congress, class: 'form-control' %>
<%= ff.select :bill_type, options_for_select(
[['House of Representatives', 'hr'],
['Senate', 's'],
['House Joint Resolution', 'hjres'],
['Senate Joint Resolution', 'sjres'],
['House Concurrent Resolution', 'hconres'],
['Senate Concurrent Resolution', 'sconres'],
['House Resolution', 'hres'],
['Senate Resolution', 'sres']]
)
%>
<%= ff.label :bill_number, 'Bill number (i.e. 67)' %>
<%= ff.number_field :bill_number, class: 'form-control' %>
<% end %>
<%= submit_tag "Submit", class: "btn btn-primary" %>
<% end %>

控制器操作

def find_by_attributes
@bill = Bill.where(bill_params).first_or_create(bill_attributes)
redirect_to bills_path(@bill)
end
def show
puts bill_params
if params[:bill]
@bill = Bill.where(bill_params).first_or_create do |bill|
bill.attributes = bill_attributes
end
else
@bill = Bill.find(params[:id])
end
@subjects = Subject.where("bill_id = ?", @bill[:id])
@bill_comments = Comment.where("target = ?", @bill[:id])
end

路由文件

...
resources :bills do
get :find_by_attributes
end
...

编辑

我在我的轨道应用程序中使用了涡轮链接宝石。

我在这里看到的是你正在呼吁

redirect_to bills_path(@bill)

理论上不是显示路径,您只需要删除" S">

redirect_to bill_path(@bill)

作为附带注释,在此行中,您不需要第一部分,因为find_b找到符合指定条件的第一条记录,您可以删除该部分。

@bill = Bill.find_by( params )

相关内容

最新更新