【问题标题】:Rails 3 & 4 conditional association syntaxRails 3 & 4 条件关联语法
【发布时间】:2015-12-15 23:46:57
【问题描述】:

嘿,我一直在尝试将 rails 应用程序从 rails 3 升级到 rails 4,而我遇到的问题之一是使用具有条件 has_one 关联的 gem,该关联在语法上适用于两者版本。见下文:

Rails 3 语法:

has_one :foo, 
  class_name: 'Gem::Foo', foreign_key: :foo_key, primary_key: :bar_key
  conditions: proc { proc_logic }

Rails 4 语法:

has_one :foo,
  -> { where( proc_logic in where clause) }, 
  class_name: 'Gem::Foo', foreign_key: :foo_key, primary_key: :bar_key

似乎在 Rails 关联上实现conditions 的两种方式是互斥的(在 Rails 4 中已弃用,在 Rails 3 中不兼容)。有没有办法达成妥协,以便代码可以在两个 Rails 版本上运行?

【问题讨论】:

  • Rails 4 也使用-> {} 作为范围。例如,使用类User,您可以创建一个范围female,导致调用User.female.all ...

标签: ruby-on-rails syntax associations conditional-statements


【解决方案1】:

Ruby 在这些方面非常灵活。你问的可以这样写。

class SomeModel < ActiveRecord::Base
  if Rails.version >= '4.0.0'
    has_one :foo,
      -> { where( proc_logic in where clause) }, 
      class_name: 'Gem::Foo', foreign_key: :foo_key, primary_key: :bar_key
  else
    has_one :foo, 
      class_name: 'Gem::Foo', foreign_key: :foo_key, primary_key: :bar_key
      conditions: proc { proc_logic }
  end
end

【讨论】:

  • 谢谢,我认为这是我将要采取的方法。它有点难看,但c'est la vie!
猜你喜欢
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
相关资源
最近更新 更多