Rails 4 has_many 的已弃用警告与订单 [英] Deprecated warning for Rails 4 has_many with order

查看:23
本文介绍了Rails 4 has_many 的已弃用警告与订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class RelatedList < ActiveRecord::Base
  extend Enumerize

  enumerize :list_type, in: %w(groups projects)

  belongs_to :content
  has_many :contents, :order => :position

end

我的 rails 应用程序中有这个模型,当我尝试在控制台中创建记录时会引发警告.

I have this model in my rails app which throws warning when I try to create records in console.

弃用警告:您的以下选项RelatedList.has_many :contents 声明已弃用: :order.请改用范围块.例如,以下内容: has_many:spam_comments, 条件: { spam: true }, class_name: 'Comment'应该改写如下: has_many :spam_comments, -> {其中 spam: true }, class_name: 'Comment'.(从/Users/shivam/Code/auroville/avorg/app/models/related_list.rb:7 调用)

DEPRECATION WARNING: The following options in your RelatedList.has_many :contents declaration are deprecated: :order. Please use a scope block instead. For example, the following: has_many :spam_comments, conditions: { spam: true }, class_name: 'Comment' should be rewritten as the following: has_many :spam_comments, -> { where spam: true }, class_name: 'Comment' . (called from at /Users/shivam/Code/auroville/avorg/app/models/related_list.rb:7)

Rails 4 似乎有用于模型的新 :order 语法,但我似乎无法在 Rails Guides 中找到文档.

It seems like Rails 4 has new :order syntax for use in models but I can't seem to find the documentation in Rails Guides.

推荐答案

在 Rails 4 中,:order 已被弃用,需要替换为 lambda 范围块,如警告中所示张贴在问题中.还有一点需要注意的是,这个范围块需要在任何其他关联选项之前传递,例如 dependent: :destroy 等.

In Rails 4, :order has been deprecated and needs to be replaced with lambda scope block as shown in the warning you've posted in the question. Another point to note is that this scope block needs to be passed before any other association options such as dependent: :destroy etc.

试试这个:

has_many :contents, -> { order(:position) } # Order by :asc by default

要指定订单方向,即@joshua-coady 和@wsprujit 建议的ascdesc,请使用:

To specify order direction, i.e. either asc or desc as @joshua-coady and @wsprujit have suggested, use:

has_many :contents, -> { order 'position desc' }

或者,使用哈希样式:

has_many :contents, -> { order(position: :desc) }

进一步参考 Active Record Scopes for has_many.

Further reference on Active Record Scopes for has_many.

这篇关于Rails 4 has_many 的已弃用警告与订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆