问题描述
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, -> {其中垃圾邮件:真},class_name:'评论'.(从/Users/shivam/Code/auroville/avorg/app/models/related_list.rb:7 调用)
似乎 Rails 4 有新的 :order 语法可用于模型,但我似乎在 Rails 指南中找不到文档.
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 建议的asc
或desc
,请使用:
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) }
进一步参考 has_many的活动记录范围代码>
.
Further reference on Active Record Scopes for has_many
.
这篇关于已弃用的 Rails 4 has_many 警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!