我在我的rails app上实现了friendly_id
。之前点击链接时,网址过去如下所示:
https://example.com/search?category_id=228
点击链接后实施friendly_id
后,它开始按以下方式提供网址:
https://example.com/search?category_id=construction-and-heavy-equipment
我在平台上实现了404
方法。当给出无效的网址时,它会重定向到404
错误页面。它适用于无效网址。
但是现在当我测试给出旧网址时,https://example.com/search?category_id=228
它仍在工作。我怎么能阻止这个?
控制器
def search_equipments
begin
if (params.keys & ['category_id', 'sub_category', 'manufacturer', 'country', 'state', 'keyword']).present?
if params[:category_id].present?
@category = Category.active.find params[:category_id]
else
@category = Category.active.find params[:sub_category] if params[:sub_category].present?
end
@root_categories = Category.active.roots
@sub_categories = @category.children.active if params[:category_id].present?
@sub_categories ||= {}
@countries = Country.active.all
@manufacturers = Manufacturer.active.all
@states = State.active.where("country_id = ?", params[:country]) if params[:country].present?
@states ||= {}
unless params[:category_id].present? && params[:sub_category].present?
params[:category_id] = @category.id if params[:category_id].present?
params[:sub_category] = @category.id if params[:sub_category].present?
end
@equipments = Equipment.active.filter(params.slice(:manufacturer, :country, :state, :category_id, :sub_category, :keyword)).order("#{sort_column} #{sort_direction}, created_at desc").page(params[:page]).per(per_page_items)
else
redirect_to root_path
end
rescue Exception => e
redirect_to root_path, :notice => "Something went wrong!"
end
end
关注
module Filterable
extend ActiveSupport::Concern
module ClassMethods
def filter(filtering_params)
results = self.where(nil)
filtering_params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results
end
end
end
答案 0 :(得分:1)
根据friendly_id
源代码,您应该使用find_by_friendly_id
。因为find方法首先通过slug查询,然后回退到常规的find方法。
# If the id is "unfriendly", it will call the original find method.
# If the id is a numeric string like '123' it will first look for a friendly
# id matching '123' and then fall back to looking for a record with the
# numeric id '123'.
#
# Since FriendlyId 5.0, if the id is a numeric string like '123-foo' it
# will *only* search by friendly id and not fall back to the regular find
# method.
#
# If you want to search only by the friendly id, use {#find_by_friendly_id}.
更改代码
@category = Category.active.find params[:category_id]
到这个
@category = Category.active.friendly.find_by_friendly_id params[:category_id]
并检查https://github.com/norman/friendly_id/issues/648#issuecomment-75172624,这是另一种解决方案,但更复杂。
答案 1 :(得分:1)
您可以通过两种方式实现这一目标:
您可以发送id
,而不是从slug
发送redirect
。
如果您在请求中找到数字controller
,则其他方法是在id
内设置一些 public class Node {
private static List<Node> nodes = new List<Node>();
private List<Node> inputs { get; set;}
private List<Node> outputs {get;set;}
protected Node() { }
protected Node(Node input, Node outPut) {
Node newNode = new Node();
nodes.Add(newNode);
newNode.inputs.Add(input);
newNode.outputs.Add(output);
}
}
代码。