Ruby on rails 如何使用命名的_作用域过滤模型中的记录
我有一个带有“描述”字段的模型“产品”。现在我想在索引页面中有一个链接,当单击该链接时,将显示描述为空白(空)的所有产品 在模型中,我定义了一个命名的_范围,如下所示Ruby on rails 如何使用命名的_作用域过滤模型中的记录,ruby-on-rails,named-scope,Ruby On Rails,Named Scope,我有一个带有“描述”字段的模型“产品”。现在我想在索引页面中有一个链接,当单击该链接时,将显示描述为空白(空)的所有产品 在模型中,我定义了一个命名的_范围,如下所示 named_scope :no_description, :conditions => { :description => "" } 我已经通过在控制台上调用Product.no\u description.count检查了命名的\u范围是否有效 据我所知,控制器应该处理来自“索引”操作链接的过滤请求,但能
named_scope :no_description, :conditions => { :description => "" }
我已经通过在控制台上调用Product.no\u description.count检查了命名的\u范围是否有效
据我所知,控制器应该处理来自“索引”操作链接的过滤请求,但能够将其与默认值(查看所有产品)区分开来
def index
@products = Product.all
...
我的问题是让控制器处理不同的请求,为视图上的链接和视图上的实际链接设置什么路由。希望我解释了我的问题。如果您的链接传入了一个参数,您可以检查该参数并在索引操作中使用命名范围:
def index
if params[:no_description]
@products = Product.no_description
else
@products = Product.all
end
end
在您看来,您可以使用以下内容:
link_to('No description', products_path(:no_description => 1))
您可以采取两种基本方法。您可以设置一个新的路由和控制器操作来显示无描述的产品,也可以使用超链接上的查询字符串参数来进行区分。我将使用第二种方法,以避免控制器因太多操作而变得混乱 假设您使用的是:
我想你有一个打字错误,应该是
Product.all
等(单数)。另外,链接到@John的末尾缺少一个括号,我已经纠正了这些错误。谢谢
<%= link_to 'Products Without Descriptions', products_path(:filter => true) %>
def index
if params[:filter]
@products = Product.no_description
else
@products = Product.all
end
...
end