【问题标题】:how to generate link to next product in same category, rails如何生成指向同一类别下一个产品的链接,rails
【发布时间】:2013-06-26 16:39:28
【问题描述】:

我想实现这样的功能。

我目前正在查看确切的产品,例如 John Deer 拖拉机,它属于拖拉机类别。 如何生成链接以便单击它会将我发送到拖拉机类别下的下一个拖拉机? 我对 Kaminari 和 Will paginate 之类的分页很熟悉,但是没有分页宝石我可以做这样的事情吗?

目前我没有任何想法要展示,或者我尝试过什么。

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby pagination


    【解决方案1】:

    当然可以,假设你有这个模型

    class Category < ActiveRecord::Base
      has_many :products
    
      def previous_product(product)
        products.where("created_at < ?", product.created_at).last
      end
    
      def next_product(product)
        products.where("created_at > ?", product.created_at).first
      end
    end
    

    您也可以将范围逻辑移至 Product 类:)

    -- 编辑--

    在视图内部,类似

    <% next_product = @category.next_product(@product) %>
    <% if next_product %>
      <%= link_to next_product.title, product_url(next_product) %>
    <% end %>
    

    【讨论】:

    • 。谢谢,如何将 next_product 添加到链接?
    • 未定义的局部变量或方法`next_product'
    • 现在工作了,它会生成正确的链接,但是当我点击它时,undefined method name' for nil:NilClass` 可能是因为它找不到其他产品?
    • 是的,看到修改后的答案!
    • 啊哈,我可能已经颠倒了条件:) 检查更新的答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 2020-04-22
    • 2013-04-05
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多